Home > Back-end >  combining and filtering array of objects into a single object in javaScript
combining and filtering array of objects into a single object in javaScript

Time:06-25

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

CodePudding user response:

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!

CodePudding user response:

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);

CodePudding user response:

You can achieve this using reduce and returning an object from it:

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

CodePudding user response:

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);
  • Related