I have an 2 array, first array:
[
{
"id": 1,
"name": "jumlah_sd",
"title": "Jumlah SD",
"value": "1222"
},
{
"id": 2,
"name": "jumlah_smp",
"title": "Jumlah SMP",
"value": "1322"
}
]
and second array with no value:
[
{
"id": 1,
"name": "jumlah_sd",
"title": "Jumlah SD"
},
{
"id": 2,
"name": "jumlah_smp",
"title": "Jumlah SMP"
},
{
"id": 3,
"name": "jumlah_sma",
"title": "Jumlah SMA"
}
]
My question is, how to push by their "id" object value in first array to second array in JavaScript? And if there is no value in other object, so the value become "value": "" in second array.
CodePudding user response:
One way to do is to create an object with the id
as the key and value
as value for easy lookup.
After that map
through the second array and add the id using the lookup object.
const arr1 = [ { "id": 1, "name": "jumlah_sd", "title": "Jumlah SD", "value": "1222" }, { "id": 2, "name": "jumlah_smp", "title": "Jumlah SMP", "value": "1322" }]
let arr2 = [ { "id": 1, "name": "jumlah_sd", "title": "Jumlah SD" }, { "id": 2, "name": "jumlah_smp", "title": "Jumlah SMP" },{ "id": 3, "name": "jumlah_sma", "title": "Jumlah SMA" }]
const idLookup = arr1.reduce((acc,{id,value}) => {
acc[id]??=value
return acc
},{})
arr2 = arr2.map((x) => ({...x, value: idLookup[x.id]||""}))
console.log(arr2)
Another approach is to use find
inside map
but it will intuitively be slower since the find
is called in each iteration inside the map
const arr1 = [ { "id": 1, "name": "jumlah_sd","title": "Jumlah SD", "value": "1222" }, { "id": 2,"name": "jumlah_smp", "title": "Jumlah SMP", "value": "1322" }]
let arr2 = [ { "id": 1, "name": "jumlah_sd", "title": "Jumlah SD" }, { "id": 2, "name": "jumlah_smp", "title": "Jumlah SMP" }, { "id": 3, "name": "jumlah_sma", "title": "Jumlah SMA" }]
arr2 = arr2.map((x) => {
const entry = arr1.find(({id}) => x.id === id)
return {...x,value:entry?.value||''}
})
console.log(arr2)