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

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

create new array of objects by mapping through object list and arrays

问题

array of objects

  1. const arrOfObj = [{ id: "id1", name: "A1", rollno: "1"}, {id: "id2", name: "A2", rollno: "2"}, { id: "id3", name: "A3", rollno: "3"}]

another object list

  1. 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

  1. 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

  1. const arrOfObj = [{ id: "id1", name: "A1", rollno: "1"}, {id: "id2", name: "A2", rollno: "2"}, { id: "id3", name: "A3", rollno: "3"}]

another object list

  1. 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

  1. const newArrOfObj = Object.entries(obj).map()

答案1

得分: 0

你可以使用 Array.prototype.map() 方法基于 arrOfObjobj 之间的映射来创建一个新的对象数组。

示例:

  1. const arrOfObj = [
  2. { id: "id1", name: "A1", rollno: "1" },
  3. { id: "id2", name: "A2", rollno: "2" }
  4. ];
  5. const obj = { "id1": "absent", "id2": "present" };
  6. const newArrOfObj = arrOfObj.map(item => {
  7. return {
  8. id: item.id,
  9. name: item.name,
  10. attendance: obj[item.id]
  11. };
  12. });
  13. 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 -->

  1. const arrOfObj = [
  2. { id: &quot;id1&quot;, name: &quot;A1&quot;, rollno: &quot;1&quot;},
  3. {id: &quot;id2&quot;, name: &quot;A2&quot;, rollno: &quot;2&quot;}
  4. ];
  5. const obj = {&quot;id1&quot;: &quot;absent&quot;, &quot;id2&quot;: &quot;present&quot;};
  6. const newArrOfObj = arrOfObj.map(item =&gt; {
  7. return {
  8. id: item.id,
  9. name: item.name,
  10. attendance: obj[item.id]
  11. };
  12. });
  13. 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:

确定