[英]JavaScript: update array of object using objects
I have one object and one is an array of objects like:我有一个 object,其中一个是一组对象,例如:
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在对象数组中,我想要使用 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基本上,我只想使用 object 和 object 数组更新文本值
Note - every time I'm getting a new object so how can I achieve this in loop注意- 每次我得到一个新的 object 那么我怎样才能在循环中实现这个
You can use map()
.您可以使用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]
.该解决方案使用object 解构来获取key
和value
,并使用obj[value]
在 object 中查找值。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.