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
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:
const myObj= myCurrentData.reduce((acc,curr)=> {
return {...acc, [curr._id]:curr.name}
}, {})