Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

convert nested object to flat data

Hi every one i have a data like this :
{
id: 1,
address: {id:100 , street: ‘Kulas Light’, suite: ‘Apt. 556’, city: ‘Gwenborough’, {…}},
company: {id:200,name: ‘Romaguera-Crona’, catchPhrase: ‘Multi-layered client-server neural-net’},
email: "Sincere@april.biz",
}

i need too set value of id to address and company

how can i convert it to this :
{
id: 1,
address:100
company:200
email: "Sincere@april.biz",
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  Object.entries(record)
     .filter((item) => typeof item[1] === "object")
     .forEach((items: any) => `${items[0]}:${items[1]?.id}`);

>Solution :

If you want to use .filter, you want the output object to have the same number of keys as the input object, so overwrite the key you’re iterating over in the forEach.

const record = {
  id: 1,
  address: {id:100 , street: 'Kulas Light', suite: 'Apt. 556', city: 'Gwenborough'},
  company: {id:200,name: 'Romaguera-Crona', catchPhrase: 'Multi-layered client-server neural-net'},
  email: "Sincere@april.biz",
};
Object.entries(record)
   .filter(entry => typeof entry[1] === "object")
   .forEach(([key, value]) => {
     record[key] = value.id;
   });
console.log(record);

A nicer way without mutating the existing object would be to use Object.fromEntries to transform the value part of each entry if necessary.

const record = {
  id: 1,
  address: {id:100 , street: 'Kulas Light', suite: 'Apt. 556', city: 'Gwenborough'},
  company: {id:200,name: 'Romaguera-Crona', catchPhrase: 'Multi-layered client-server neural-net'},
  email: "Sincere@april.biz",
};
const result = Object.fromEntries(
  Object.entries(record)
    .map(([key, value]) => [
      key,
      typeof value === 'object' ? value.id : value
    ])
);
console.log(result);

typeof null gives 'object' too, though – if that’s a possibility, you can instead use for the value:

value?.id ?? value
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading