catlovespurple
catlovespurple

Reputation: 702

Get an object from two nested array in Javascript

I want to have an object from two arrays and I did it in the following way.

for (var j = 0; j < rawDataRows.length; j++) {
        for (var i = 0; i < categories.length; i++) {
            var category = categories[i];
            var rowValue = rawDataRows[j];
            // here I do got the right value for category
            console.log(category); 
            console.log(rowValue);
            // but the following line doesn't interpret category as a variable
            formattedDataRows.push({category: rowValue});
        }
}

I was assuming I can get something like :

[{"category1": "value1"},{"category2": "value2"}, {"category3": "value3"}]

However, it turned out I got:

[{"category": "value1"}, {"category": "value2"}, {"category": "value3"}]

Can anyone point me where I am wrong? Also, if you have a better way achieving the goal, leave a comment please. Javascript only no jQuery or other framework. Thanks!

Upvotes: 0

Views: 44

Answers (3)

CoderPi
CoderPi

Reputation: 13211

You can use categories[i].toString(); to get strings as you wished:

var categories = ["category1", "category2", "category3"];
var rawDataRows = ["value1", "value2", "value3"];
var formattedDataRows = [];

for (var j = 0; j < rawDataRows.length; j++) {
  for (var i = 0; i < categories.length; i++) {
    var category = categories[i].toString();
    var rowValue = rawDataRows[j].toString();

    var tmpObj = {}
    tmpObj[category] = rowValue
    formattedDataRows.push(tmpObj);
    
   //formattedDataRows.push({[category]: rowValue});
  }
}

document.write(JSON.stringify(formattedDataRows))

Upvotes: 1

spozun
spozun

Reputation: 882

If you want both values to increment together (as it seems), also assuming the length of categories is the same length as rawdataRows, I think you really want a single loop instead of two loops:

for (var i = 0; i < categories.length; i++) {
            var category = categories[i];
            var rowValue = rawDataRows[i];

Upvotes: 1

user1106925
user1106925

Reputation:

Object literal syntax In ECMAScript 5 and lower doesn't allow you to specify a variable identifier as property name. Instead create the object first and then use bracket notation.

var o = {};
o[category] = rowValue;
formattedDataRows.push(o);

With ECMAScript 6, you can do this:

formattedDataRows.push({[category]: rowValue});

though of course support for that syntax is limited at this point in time.

Upvotes: 5

Related Questions