Reputation: 3
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
let myFinalData = {
D01: "Lunetts",
D02: "Glasses",
D03: "Auros"
}
i just want to use the values of _id and name
Upvotes: -1
Views: 36
Reputation: 673
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. 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);
Upvotes: 0
Reputation: 424
You can achieve this using reduce and returning an object from it:
const myObj= myCurrentData.reduce((acc,curr)=> {
return {...acc, [curr._id]:curr.name}
}, {})
Upvotes: 0
Reputation: 63550
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);
Upvotes: 1
Reputation: 1259
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!
Upvotes: 1