I am having an array values with multiple values< i want that array values to split into different objects

let array = [{"condition":"equals","field_name":"name","value":["Company B","Company D"]}]

Expected output:

[{"condition": "equals",
    "field_name": "name",
    "value": ["Company B"]
    "condition": "equals",
    "field_name": "name",
    "value": ["Company D"]

3 Answers

Slawomir Chodnicki On

Something like this will work:

let things = [{"condition":"equals","field_name":"name","value":["Company B", "Company D"]}];

function expand(xs){
 var results = [];
 xs.forEach(item => {
   if (item.value && item.value.length > 1){
     results.push(...item.value.map( v => Object.assign({}, item, {value: [v]})))
 return results;


Michael On
let newArr = array.map(item => item.value.map(val => { return { ...item, value: val} }));  

This should achieve the desired result of the question if I understood correctly.

wentjun On

I might be over-complicating things, but here is my suggested solution.

You can make use of Array.map(), and iterate for each object within the original array, followed by iterating within value, such that there is one object for each element within the value property. This is followed by concatenating them to form the resulting array.

let array = [{"condition":"equals","field_name":"name","value":["Company B","Company D"]}];

const res = [].concat(...array.map(({'condition', 'field_name', 'value'}) =>
  value.map(value => ({'condition', 'field_name', 'value'}))