英文:
create new array of objects by mapping through object list and arrays
问题
array of objects
const arrOfObj = [{ id: "id1", name: "A1", rollno: "1"}, {id: "id2", name: "A2", rollno: "2"}, { id: "id3", name: "A3", rollno: "3"}]
another object list
const obj = {"id1": "absent", "id2": "present"}
create a new array of obj by mapping through "obj" and map through "arrOfObj" and check if "id" matches then create
const newArrOfObj = [{ id: "id1", name: "A1", attendance: "absent"}, {id: "id2", name: "A2", attendance: "present"}]
not sure how to do
const newArrOfObj = Object.entries(obj).map()
英文:
I am new to programming world. I would like to know how can I do the following.
array of objects
const arrOfObj = [{ id: "id1", name: "A1", rollno: "1"}, {id: "id2", name: "A2", rollno: "2"}, { id: "id3", name: "A3", rollno: "3"}]
another object list
const obj = {"id1": "absent", "id2": "present"}
create a new array of obj by mapping through "obj" and map through "arrOfObj" and check if "id" matches then create
const newArrOfObj = [{ id: "id1", name: "A1", attendance: "absent"}, {id: "id2", name: "A2", attendance: "present"}]
not sure how to do
const newArrOfObj = Object.entries(obj).map()
答案1
得分: 0
你可以使用 Array.prototype.map() 方法基于 arrOfObj
和 obj
之间的映射来创建一个新的对象数组。
示例:
const arrOfObj = [
{ id: "id1", name: "A1", rollno: "1" },
{ id: "id2", name: "A2", rollno: "2" }
];
const obj = { "id1": "absent", "id2": "present" };
const newArrOfObj = arrOfObj.map(item => {
return {
id: item.id,
name: item.name,
attendance: obj[item.id]
};
});
console.log(newArrOfObj);
英文:
You can use Array.prototype.map() method to create a new Array of objects based on the mapping between the arrOfObj
and obj
.
Example:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const arrOfObj = [
{ id: "id1", name: "A1", rollno: "1"},
{id: "id2", name: "A2", rollno: "2"}
];
const obj = {"id1": "absent", "id2": "present"};
const newArrOfObj = arrOfObj.map(item => {
return {
id: item.id,
name: item.name,
attendance: obj[item.id]
};
});
console.log(newArrOfObj);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论