2

I have data like this:

var data = {
  value1: ["a", "b", "c"],
  value2: [1, 2, 3]
}

I want to convert it to:

var newData = [
  {value1: "a", value2: 1},
  {value1: "b", value2: 2},
  {value1: "c", value2: 3}
]

How can I achieve this with javascript?

6
  • Are you open to lodash/underscore? Commented Jan 6, 2017 at 7:40
  • Loop over value1, and push little objects made from the value from value1 and the value from value2 at the same index onto an array. Commented Jan 6, 2017 at 7:44
  • Are the names value1 and value2 fixed? Commented Jan 6, 2017 at 7:45
  • @torazaburo I do not want to use lodash or underscore, and value1 and value2 are not fixed. Commented Jan 6, 2017 at 8:12
  • Are the lengths of the individual arrays guaranteed to be the same? Commented Jan 6, 2017 at 9:05

5 Answers 5

9

Use Array#map method to generate the array.

var data = {
  value1: ["a", "b", "c"],
  value2: [1, 2, 3]
};

// iterate over the first property
var res = data.value1.map(function(v, i) {
  // generate the array object element
  return {
    value1: v,
    value2: data.value2[i]
  }
});

console.log(res);


UPDATE 1 : If the property names are unknown then you can do something like this.

var data = {
  value1: ["a", "b", "c"],
  value2: [1, 2, 3]
};

// get all property names
var keys = Object.keys(data);

// iterate over the first property name array
var res = data[keys[0]].map(function(v, i) {
  // generate the object by iterating over the keys array
  return keys.reduce(function(obj, k) {
    // define the object property
    obj[k] = data[k][i];
    // return the objet reference
    return obj;
    // set initial value as empty object
  }, {});
});

console.log(res);


UPDATE 2 : If array length can be different then you need to get the larger array from the collection.

var data = {
  value1: ["a", "b", "c", "d"],
  value2: [1, 2, 3],
  value3: [1, 2, 3, 5, 6, 7, 8]
};

// get all property names
var keys = Object.keys(data);

// iterate over the largest array
var res = data[
  // get the largest array holding key from the keys array  
  keys.reduce(function(k, k1) {
    return data[k1].length > data[k].length ? k1 : k;
  })
].map(function(v, i) {
  // generate the object by iterating over the keys array
  return keys.reduce(function(obj, k) {
    // check element exist in the array by comparing
    // the length and index
    if (data[k].length > i)
    // define the property if value exist in index
      obj[k] = data[k][i];
    // return the objet reference
    return obj;
    // set initial value as empty object
  }, {});
});

console.log(res);

Sign up to request clarification or add additional context in comments.

4 Comments

This assume both are of the same size.
@Ghasan : that's the expected input
@Ghasan : I will add solution for that's too
you like to loooooop. ;)
4

You could use a complete dynamic version for it, without giving keys.

It works for arrays with unequal length as well.

function pivot(object) {
    return Object.keys(object).reduce(function (r, k) {
        object[k].forEach(function (a, i)  {
            r[i] = r[i] || {};
            r[i][k] = a;
        });
        return r;
    }, []);
}

console.log(pivot({ value1: ["a", "b", "c"], value2: [1, 2, 3] }));
console.log(pivot({ value1: ["a", "b", "c", "d"], value2: [1, 2, 3], value3: [1, 2, 3, 5, 6, 7, 8] }));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

3

var data = {
  value1: ["a", "b", "c"],
  value2: [1, 2, 3]
}

var newData  = [];


for (var i=0; i<data.value1.length; i++) {
      var obc = {}
          obc['value1'] = data.value1[i];
          obc['value2'] = data.value2[i];
      newData.push(obc)
}

console.log(newData)

Comments

0
var data = {
  value1: ["a", "b", "c"],
  value2: [1, 2, 3]
}

var newData = [];

for(var i=0;i<data.value1.length;i++){
   var obj = {
       value1: data.value1[i],
       value2: data.value2[i]
   }
   newData.push(obj);
}

1 Comment

For most answers it is a good idea to add an explanation to show how the code works, this helps other people with less programming experience understand what the code does.
0

Try this:

  var data = {
        value1: ["a", "b", "c"],
        value2: [1, 2, 3]
    };
    
    var arr = [];
    
    data[Object.keys(data)[0]].forEach(function (value, index) {
        arr[index] = {};
        Object.keys(data).forEach(function (key) {
            arr[index][key]=data[key][index];
        });
    });
    
    console.log(arr)

With this solution you can modify the value1, value2 props, or you can add more if needed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.