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)));
                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);
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With