-1

I have an array of objects which is coming from server response.

Array structure:

[
  {
    col1: ["a", "b"],
    col2: ["c", "d"]
  },

  {
    col1: ["e", "f"],
    col2: ["g", "h"]
  }
]

I want the desired output array to be in this form:

[
  {
    col1: "b",
    col2: "d"
  },

  {
    col1: "f",
    col2: "h"
  }
]

Basically I want to convert the Object keys Value which is an array initially to a single value and that value will be second element of the Object keys array.

I am able to do the conversion by converting Object Keys array to comma seperated string using toString(), then do string.split(",")[1] but I am not able to iterate through the Object keys.

Would prefer the inputs in ES6 using map for iteration

dodov
  • 5,206
  • 3
  • 34
  • 65

3 Answers3

0

The code below should work as per your specification.

var arr = [ {col1: ["a","b"], col2: ["c","d"] }, {col1: ["e","f"], col2: ["g","h"] } ]


// [ {col1: "b" , col2: "d" }, {col1: "f", col2: "h" } ]

arr2 = [];

arr.forEach(e => {
  let currObj = {};
  Object.keys(e).forEach(f => {
    currObj[f] = e[f][1]
  })
  arr2.push(currObj)
})

console.log(arr2);
Mμ.
  • 8,382
  • 3
  • 26
  • 36
0

Possible solution using Array#reduce and Object.keys.

var arr = [ {col1: ["a","b"], col2: ["c","d"] }, {col1: ["e","f"], col2: ["g","h"] } ],
    res = arr.reduce(function(s,a) {
      var obj = {};
      Object.keys(a).map(function(c) {
        obj[c] = a[c][1];
      })
      s.push(obj);
      return s;
    }, []);
    
    console.log(res);
kind user
  • 40,029
  • 7
  • 67
  • 77
0

You could use a combination of Array#map, Object.assign and spread syntax ... with an inner mapping of a new object with the wanted key/value.

var data = [{ col1: ["a", "b"], col2: ["c", "d"] }, { col1: ["e", "f"], col2: ["g", "h"] }],
    result = data.map(o => Object.assign({}, ...Object.keys(o).map(k => ({ [k]: o[k][1] }))));

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