bito_
bito_

Reputation: 179

JS - Fill an associative array using a loop

I'm trying to fill an JS array using a loop but is not working This is my code:

words = ["one", "two", "three", "four"];
words_formated = [];

for( var i=0 ; i<words.length ; i++ ){
    words_formated.push({words[i]: "<i>"+ words[i] +"</i>"});
}

Upvotes: 1

Views: 394

Answers (5)

user1636522
user1636522

Reputation:

Try this :

var words = ['one', 'two', 'three', 'four'],
    words_formated = [],
    item;
for (var i = 0; i < words.length; i++) {
    item = {};
    item[words[i]] = '<i>' + words[i] + '</i>';
    words_formated.push(item);
}

According to your own code, the result will be :

[
    { one   : "<i>one</i>"   }, 
    { two   : "<i>two</i>"   }, 
    { three : "<i>three</i>" }, 
    { four  : "<i>four</i>"  }
]

Array :

var a = (1, 2, 3); // a sequence of numbers (returns the last one)
a // 3
var a = [1, 2, 3]; // an array
a // [1, 2, 3]

Fails :

var k = ['name'];
var o = { k[0]: 'value' }; // SyntaxError: Unexpected token [

Passes :

var k = ['name'];
var o = {};
o[k[0]] = 'value';
o // Object {name: "value"}

Upvotes: 1

Stuart Miller
Stuart Miller

Reputation: 657

I also got an error with trying to use the array key to directly assign the object property name, this worked:

words = ["one", "two", "three", "four"];
words_formated = [];

for( var i=0; i<words.length; i++ ){
    var item = words[i]
    words_formated.push({item: "<i>"+ words[i] +"</i>"});
}

jsfiddle here

Upvotes: 1

vaibhav silar
vaibhav silar

Reputation: 3085

As your are pushing an object into array words_formated.push({words[i]: "<i>"+ words[i] +"</i>"}); , the key name words[i] is not correct

The problem will get solved if you write

words_formated.push({words: "<i>"+ words[i] +"</i>"});

and its best practice if you define word array correctly as words = ["one", "two", "three", "four"];

Upvotes: 1

Curlas
Curlas

Reputation: 899

Use like an array:

words = ["one", "two", "three", "four"];
var words_formated=[];

for( var i=0 ; i<words.length ; i++ ){

    words_formated[words[i]]= "<i>"+ words[i] +"</i>";
}

console.log(words_formated);

Upvotes: 0

Praveen
Praveen

Reputation: 56501

words = ("one", "two", "three", "four"); //wrong

Instead use within array block

words = ["one", "two", "three", "four"];

Upvotes: 0

Related Questions