1

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.

1
  • just an idea . convert first array to a object for easy lookup then map through the second array and add the value Commented Nov 5, 2022 at 7:27

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.