Home > Software engineering >  JavaScript: update array of object using objects
JavaScript: update array of object using objects

Time:09-28

I have one object and one is an array of objects like :

let obj = {
    id:'1',
    v1: '4',
    v2: '2',
    v3: '3',
}


const arr= [{key:1, value: 'v1'},{key:2, value:'v2'}]

here in the array of objects, I want concat values like this using key and value of obj

arr= [{key:1, value: 'v1:4'},{key:2, value:'v2:2'}]

basically, I just want to update the text value like this using object and an array of object

Note - every time I'm getting a new object so how can I achieve this in loop

CodePudding user response:

You can use map().

let obj = {
  id: "1",
  v1: "4",
  v2: "2",
  v3: "3",
};

const arr = [
  { key: 1, value: "v1" },
  { key: 2, value: "v2" },
];

const result = arr.map(({ key, value }) => ({ key, value: `${value}:${obj[value]}` }));
console.log(result)

This solution uses object destructuring to get the key and value and looks up the values in the object using obj[value].

CodePudding user response:

Try this :

let obj = {
    id: '1',
    v1: '4',
    v2: '2',
    v3: '3',
};

const arr= [{key:1, value: 'v1'},{key:2, value:'v2'}];

arr.forEach((arrayObj, index) => {
    arr[index].value = Object.keys(obj).includes(arrayObj.value) ?  `${arrayObj.value}:${obj[arrayObj.value]}` : arrayObj.value
});

console.log(arr);

  • Related