-1

I have a array as follows:

data = [
  {
    "data": {
        "id":1,
        "vol":"0.0"
        "details":{
            "ABC":"8.30",
            "OFG":"13.85",
            "SPG":"70.80"
        }
        
    }
  },
   {
    "data": {
        "id":2,
        "vol":"1.0"
        "details":{
            "ABC":"3.30",
            "OFG":"15.85",
            "SPG":"70.80"
        }
        
    }
  }
]

I want to make an arrays from above array such that data inside details object is every element comes outside. So in my final array there will not be details object. I just want to bring all attributes of details object with other object. So my final array will look something like this

data = [
{
    "data": {
        "id":1,
        "vol":"0.0"
        "ABC":"8.30",
        "OFG":"13.85",
        "SPG":"70.80"
        
    }
  },
   {
        "data": {
        "id":1,
        "vol":"0.0"
        "ABC":"8.30",
        "OFG":"13.85",
        "SPG":"70.80"
        
    }
  }
];

How can I do that?

Roma
  • 23
  • 3

2 Answers2

2

You can use Array#map with object destructuring.

const arr=[{data:{id:1,vol:"0.0",details:{ABC:"8.30",OFG:"13.85",SPG:"70.80"}}},{data:{id:2,vol:"1.0",details:{ABC:"3.30",OFG:"15.85",SPG:"70.80"}}}];
let res = arr.map(({data: {details, ...rest}}) => ({data : {...rest, ...details}}));
console.log(res);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • Hi If I want to do same thing with data. means getting all attributes out of data obj. how can I do that? – Roma Jan 21 '23 at 04:23
  • 1
    @Roma You mean like `let res = arr.map(({data: {details, ...rest}}) => ({...rest, ...details}));`? – Unmitigated Jan 21 '23 at 04:24
  • @Roma Simply remove the `{ data:` and the corresponding `}` in the return. Please read the documentation: [Destructuring assignment](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), [Object initializer](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer). – Sebastian Simon Jan 21 '23 at 04:25
  • { "id":1, "vol":"0.0" "ABC":"8.30", "OFG":"13.85", "SPG":"70.80" } – Roma Jan 21 '23 at 04:27
  • Means I want array elements without data and details object as I posted in my comment just above – Roma Jan 21 '23 at 04:27
  • how can I do that. Is it possible to update your code for this? – Roma Jan 21 '23 at 04:29
  • 1
    @Roma I already sent the code in my previous comment. – Unmitigated Jan 21 '23 at 04:38
0

You could make use of the Spread Operator and do something like this:

const builtData = originalData.map(({ data }) => ({
  data: {
    id: data.id,
    vol: data.vol,
    ...data.details
  }
}))