-1

I am looking at an object with the following structure:

[
  [
    {
      "attr1":"1",
      "attr2":"2",
      "attr3":"3"
    }
  ],
  [
    {
      "attr1":"1",
      "attr2":"2",
      "attr3":"3"
    }
  ],
  [
    {
      "attr1":"1",
      "attr2":"2",
      "attr3":"3"
    }
  ]
]

Just focusing on the structure of it, all I need to do with this object is to re-arrange it so that it ends up with the following structure:

[
  {
    "attr1":"1",
    "attr2":"2",
    "attr3":"3"
  },
  {
    "attr1":"1",
    "attr2":"2",
    "attr3":"3"
  },
  {
    "attr1":"1",
    "attr2":"2",
    "attr3":"3"
  }
]

How can this be done in either pure Javascript or in core jQ library?

Dwhitz
  • 1,250
  • 7
  • 26
  • 38
BinaryCat
  • 1,220
  • 2
  • 17
  • 32
  • So you just want to take the first element of each inner array? You could get away with just `myArray.map(x=>x[0])`. – Eric Dobbs Apr 18 '17 at 19:48

3 Answers3

2

So, you just need to remove the second-level arrays. Easily done with Array.map().

var old = [
  [
    {
      "attr1":"1",
      "attr2":"2",
      "attr3":"3"
    }
  ],
  [
    {
      "attr1":"1",
      "attr2":"2",
      "attr3":"3"
    }
  ],
  [
    {
      "attr1":"1",
      "attr2":"2",
      "attr3":"3"
    }
  ]
];

// Map loops through an array and returns a new array filled with whatever the 
// supplied callback function returns. 
var newArry = old.map(function(value){
  // Get the first object stored in the second-level array, but not the array itself
  return value[0];  
});

console.log(newArry);
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

Array#reduce may be helpful.

var arr = [[{"attr1":"1","attr2":"2","attr3":"3"}],[{"attr1":"1","attr2":"2","attr3":"3"}],[{"attr1":"1","attr2":"2","attr3":"3"}]], 
    res = arr.reduce((a,b) => a.concat(b));

    console.log(res);
kind user
  • 40,029
  • 7
  • 67
  • 77
0

You could use Array#concat with a spread syntax ....

var data = [[{ attr1: "1", attr2: "2", attr3: "3" }], [{ attr1: "1", attr2: "2", attr3: "3" }], [{ attr1: "1", attr2: "2", attr3: "3" }]],
    flat = [].concat(...data);

console.log(flat);
.as-console-wrapper { max-height: 100% !important; top: 0; }

ES5

var data = [[{ attr1: "1", attr2: "2", attr3: "3" }], [{ attr1: "1", attr2: "2", attr3: "3" }], [{ attr1: "1", attr2: "2", attr3: "3" }]],
    flat = [].concat.apply([], data);

console.log(flat);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392