0

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]};
    }
1
  • I would prefer you to use loadash. Commented Apr 11, 2016 at 18:47

3 Answers 3

2

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} 
Sign up to request clarification or add additional context in comments.

Comments

0

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;

Comments

0

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;
},{});

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.