创建新的对象数组,通过映射遍历对象列表和数组。

huangapple go评论73阅读模式
英文:

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() 方法基于 arrOfObjobj 之间的映射来创建一个新的对象数组。

示例:

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: &quot;id1&quot;, name: &quot;A1&quot;, rollno: &quot;1&quot;},
 {id: &quot;id2&quot;, name: &quot;A2&quot;, rollno: &quot;2&quot;}
];

const obj = {&quot;id1&quot;: &quot;absent&quot;, &quot;id2&quot;: &quot;present&quot;};

const newArrOfObj = arrOfObj.map(item =&gt; {
  return {
    id: item.id,
    name: item.name,
    attendance: obj[item.id]
  };
});

console.log(newArrOfObj);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月8日 20:31:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75385833.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定