Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Is there a simple way to get the values for every occurrence of a specific key in nested JSON

I have a JSON structure similar to this:

[
  {
    cells: [
     { id: "1", cellType: 3, widget: { id: 1, description: "myDesc"} },
     { id: "2", cellType: 4, widget: { id: 2, description: "myDesc2"} }
    ]
  },
  {
    cells: [
      { id: "3", cellType: 5, widget: { id: 3, description: "myDesc3"} }
    ]
  },
  ...
]

How do I get the value of every widget into a separate array using EcmaScript (or anything that's available in Angular 2+), and without using a library (including JQuery)? I need a final array like this:

[
  {
    id: 1,
    description: "myDesc"
  },
  {
    id: 2,
    description: "myDesc2"
  },
  ... 
]

Update

(and thanks to @Felix Kling for the 1st part) - I found I can get all of the widgets with this:

JSON.parse(json)[0].forEach( c => c.cells.forEach( c2 => console.log(c2.widget)));
like image 350
Chris Halcrow Avatar asked Jan 02 '23 00:01

Chris Halcrow


2 Answers

You can use .map() with .reduce()

let input = [
  {
    cells: [
     { id: "1", cellType: 3, widget: { id: 1, description: "myDesc"} },
     { id: "1", cellType: 4, widget: { id: 2, description: "myDesc2"} }
    ]
  },
  {
    cells: [
      { id: "3", cellType: 5, widget: { id: 3, description: "myDesc3"} }
    ]
  },
];

let result = input.reduce((result, current) => {
  return result.concat(current.cells.map(x => x.widget));
}, [])

console.log(result);
like image 64
mickl Avatar answered Jan 13 '23 18:01

mickl


You can use .map() and .concat() to get the desired result:

let data = [{
  cells: [
    { id: "1", cellType: 3, widget: { id: 1, description: "myDesc"} },
    { id: "1", cellType: 4, widget: { id: 2, description: "myDesc2"} }
  ]}, {
  cells: [
      { id: "3", cellType: 5, widget: { id: 3, description: "myDesc3"} }
  ]
}];

let result = [].concat(...data.map(({cells}) => cells.map(({widget}) => widget)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 31
Mohammad Usman Avatar answered Jan 13 '23 19:01

Mohammad Usman