Home > database >  Convert Nested object into custom array of objects: Javascript
Convert Nested object into custom array of objects: Javascript

Time:12-08

I am having array of objects that look like this

const test = {
  a: { name: "A", selected: [1, 2, 3], display: [1, 2, 3] },
  b: { name: "B", selected: [4, 5, 6], display: [4, 5, 6] },
  c: { name: "C", selected: [7, 8, 9], display: [7, 8, 9] },
  d: { name: "D", selected: [], display: [] }
};

I want the above to be converted as below


const output = [
  { field: "A", selectedValues: [1, 2, 3] },
  { field: "B", selectedValues: [4, 5, 6] },
  { field: "C", selectedValues: [7, 8, 9] }
];

Basically key in the input object to be made as field in the final object of that array and selected in input object should be made as selectedValues in the final object. Note only the object that has some entries selected should be put into final arrray

Also when all the objects in the input object have selected as empty then just return empty array else return the above output.

Code that I tried


const result = Object.entries(test).map(([name, v]) => ({
  field: name,
  selectedValues: v
}));

console.log(result);

CodePudding user response:

Because you want

selected in input object should be made as selectedValues in the final object.

you should navigate to the .selected property (the subarray) while mapping, instead of referencing the whole object. Afterwards, filter by whether that array has any values in it.

const test = {
  a: { name: "A", selected: [1, 2, 3], display: [1, 2, 3] },
  b: { name: "B", selected: [4, 5, 6], display: [4, 5, 6] },
  c: { name: "C", selected: [7, 8, 9], display: [7, 8, 9] },
  d: { name: "D", selected: [], display: [] }
};


const result = Object.entries(test)
  .map(([name, obj]) => ({
    field: name,
    selectedValues: obj.selected
  }))
  .filter(({ selectedValues }) => selectedValues.length);

console.log(result);

  • Related