Home > Mobile >  Type script: extract array in object
Type script: extract array in object

Time:06-16

I have object as below.

{ id: 1, property: [2,3] }

How could I change to

[ { id: 1, property: 2 }, { id: 1, property: 3 } ]

CodePudding user response:

using the map method, you map each item to another item

Here you take the id from each item and the value at index in the property array

const input = [ { id: 1, property: [2,3] } ];

const result = input[0].property.map((value, index) => ({
  id: input[0].id,
  property: value
}));

console.log(JSON.stringify(result, null, 2));

see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

CodePudding user response:

if the input is an array of elements you may use nested map and flat

const x = [
  {id: 1, property: [2, 3]},
  {id: 3, property: [5, 6]},
];
const result = x.map(item => item.property.map(prob => ({id: item.id, property: prob}))).flat();
console.log(result)

CodePudding user response:

const input = [ { id: 1, property: [2,3] } ];

const output = [];

input.forEach(obj => {
    if (Array.isArray(obj.property)) {
        obj.property.forEach(property => output.push({...obj, property}));
    } else {
        output.push(obj);
    }
});

console.log(output);

  • Related