Wouter van Dijke
Wouter van Dijke

Reputation: 682

How do I create objects from values in an array in Node.js?

I have an array consisting of a list of words, and a wordcount and ID for each word. Sort of like:

var array = [[word1, word2, word3],[3,5,7],[id1,id2,id3]]

Now I want to create an object for each word with the word as the name and the count and ID as values. So it would look like this:

var word1 = {count: 3, id: 'id1'}

How do I achieve this? I tried doing it using a for-loop as shown below, but it doesn't work. How could I set the name of each object from the values in the array?

for (var y=0; y < array[0].length; y++) {
        var array[0][y] = {count: array[1][y], id: array[2][y]};
    }

Upvotes: 0

Views: 76

Answers (3)

Devank
Devank

Reputation: 159

Loadash

var array = [['word1', 'word2', 'word3'],[3,5,7],['id1','id2','id3']]

var output = _.reduce(array[0], function (output, word, index) {
    output[word] = {count:array[1][index],id:array[2][index]};
  return output;
},{});

Upvotes: 0

Rhys Bradbury
Rhys Bradbury

Reputation: 1707

If you know that the array [0] are the ordered keys, and array[1] are the count and array[2] are the ids then:

var array = [[word1, word2, word3],[3,5,7],[id1,id2,id3]];

var orderedKeysArray = array[0];
var orderedCountArray = array[1];
var orderedIdArray = array[2];

//maybe add some code here to check the arrays are the same length?

var object = {};

//add the keys to the object
for(var i = 0; i < orderedKeysArray.length; i++) {
  object[orderedKeys[i]] = {
    count: orderedCountArray[i],
    id: orderedIdArray[i]
  };
}

Then you can refer to the object for the vars like so:

object.word1;
object.word2;
object.word3;

Upvotes: 0

AKS
AKS

Reputation: 19831

Instead of having individual objects you could add the words in one dict object like this:

var words = {};

for (var y=0; y < array[0].length; y++) {
    words[array[0][y]] = {count: array[1][y], id: array[2][y]};
}

And, you can access word1 as following:

words['word1'] // {count: 1, id: id1} 

// if the word1 doesn't contain spaces, you could also use
words.word1 //  {count: 1, id: id1} 

Upvotes: 2

Related Questions