简体   繁体   English

在javascript中将对象数组组合和过滤为单个对象

[英]combining and filtering array of objects into a single object in javaScript

 let myCurrentData = [ { _id: "D01", name: "Lunetts", profession: "shop", }, { _id: "D02", name: "Glasses", profession: "keeper", }, { _id: "D03", name: "Auros", profession: "UiiSii", }, ];

Above is my myCurrentData, I want to convert this array into a final object like the following以上是我的 myCurrentData,我想将此数组转换为最终对象,如下所示

 let myFinalData = { D01: "Lunetts", D02: "Glasses", D03: "Auros" }

i just want to use the values of _id and name我只想使用 _id 和 name 的值

 const myCurrentData = [ { _id: "D01", name: "Lunetts", profession: "shop", }, { _id: "D02", name: "Glasses", profession: "keeper", }, { _id: "D03", name: "Auros", profession: "UiiSii", }, ]; const finalObject = myCurrentData .map((eachObject) => { const { profession, name, _id } = eachObject; return { [_id]: name, }; }) .reduce((prev, current) => { return { ...prev, ...current, }; }, {}); console.log("finalObject is", finalObject);

Hope it works!希望它有效!

Use a simple loop to create a new object. 使用一个简单的循环来创建一个新对象。

 const data=[{_id:"D01",name:"Lunetts",profession:"shop"},{_id:"D02",name:"Glasses",profession:"keeper"},{_id:"D03",name:"Auros",profession:"UiiSii"}]; const out = {}; for (const obj of data) { out[obj._id] = obj.name; } console.log(out);

You can achieve this using reduce and returning an object from it:您可以使用 reduce 并从中返回一个对象来实现此目的:

const myObj=  myCurrentData.reduce((acc,curr)=> {
    return {...acc, [curr._id]:curr.name}
  
}, {})

You could take advantages of the Object.entries method combined with a forEach loop to get the properties name and values and add it to your previously declare myFinalData Object.您可以利用结合 forEach 循环的 Object.entries 方法来获取属性名称和值,并将其添加到您之前声明的 myFinalData 对象中。 Something like this could be what you are looking for.像这样的东西可能是你正在寻找的东西。 Hope it helps, bud.希望它有帮助,伙计。

const myCurrentData = [
  {
    _id: "D01",
    name: "Lunetts",
    profession: "shop",
  },
  {
    _id: "D02",
    name: "Glasses",
    profession: "keeper",
  },
  {
    _id: "D03",
    name: "Auros",
    profession: "UiiSii",
  },
];


 const myFinalData = {}
Object.entries(myCurrentData).forEach(([k,v]) => { myFinalData[v['_id']] = v['name']})

console.log(myFinalData);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM