convert nested object to flat data

Advertisements

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",
}

  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

Leave a ReplyCancel reply