-1

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

1
  • 2
    What have you tried so far? Object.fromEntries and myCurrentData.map should help Commented Jun 24, 2022 at 16:52

4 Answers 4

1

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Reaching for map and then reduce is making the code way too complicated when there is a far simpler alternative.
1

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

Comments

0

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

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.