Home > OS >  convert single value array within a nested object to a single value javascript
convert single value array within a nested object to a single value javascript

Time:09-22

I have a nested object where I'd like to convert an array of a single value group, into a single value:

real_data = [
  [
    {x: 1, group: [1]},
    {x: 9, group: [2]},
    {x: 3, group: [3]}
  ],
  [
    {x: 2, group: [1]},
    {x: 4, group: [2]},
    {x: 10, group: [3]}
  ],
  [
    {x: 1, group: [1]},
    {x: 5, group: [2]},
    {x: 12, group: [3]}
  ],
  [],
    [
    {x: 1, group: [1]},
    {x: 5, group: [2]},
    {x: 12, group: [3]}
  ]
]

I've tried using map here but have been struggling due to the nested nature of the array. I also tried and struggled with some nested for loops. The desired output is:

desired_output = [
  [
    {x: 1, group: 1},
    {x: 9, group: 2},
    {x: 3, group: 3}
  ],
  [
    {x: 2, group: 1},
    {x: 4, group: 2},
    {x: 10, group: 3}
  ],
  [
    {x: 1, group: 1},
    {x: 5, group: 2},
    {x: 12, group: 3}
  ],
  [],
    [
    {x: 1, group: 1},
    {x: 5, group: 2},
    {x: 12, group: 3}
  ]
]

Any help appreciated!!

CodePudding user response:

It is simple.

  1. Loop complete outer array
  2. Loop inner array
  3. Set value of group in inner array
real_data = [
  [
    {x: 1, group: [1]},
    {x: 9, group: [2]},
    {x: 3, group: [3]}
  ],
  [
    {x: 2, group: [1]},
    {x: 4, group: [2]},
    {x: 10, group: [3]}
  ],
  [
    {x: 1, group: [1]},
    {x: 5, group: [2]},
    {x: 12, group: [3]}
  ],
  [],
    [
    {x: 1, group: [1]},
    {x: 5, group: [2]},
    {x: 12, group: [3]}
  ]
];

var desiredOutput = real_data.map( elements => {
    let newElements = elements.map(element => {
        element.group = element.group[0];
        return element;
    });
    return newElements;
})

CodePudding user response:

You can achieve the desired result without modifying the original input -

const input =
  [[{x:1,group:[1]},{x:9,group:[2]},{x:3,group:[3]}],[{x:2,group:[1]},{x:4,group:[2]},{x:10,group:[3]}],[{x:1,group:[1]},{x:5,group:[2]},{x:12,group:[3]}],[],[{x:1,group:[1]},{x:5,group:[2]},{x:12,group:[3]}]]

const output =
  input.map(x => x.map(({ group: [group], ...y }) => ({ ...y, group })))
  
console.log(output)

[
  [
    {x:1,group:1},
    {x:9,group:2},
    {x:3,group:3}
  ],
  [
    {x:2,group:1},
    {x:4,group:2},
    {x:10,group:3}
  ],
  [
    {x:1,group:1},
    {x:5,group:2},
    {x:12,group:3}
  ],
  [],
  [
    {x:1,group:1},
    {x:5,group:2},
    {x:12,group:3}
  ]
]

CodePudding user response:

based on the desired output you can use the following

real_data.map(o=>{
    return o.map(p=>{
        return {...p, group:parseInt(p.group.toString(),10)}
    })
})
  • Related