Reputation: 2439
I'm trying add items in object in for loop , but last item always rewrites values that I added before. P/S I've posted similar question before but code was too complicated , I made sample to explain my problem .
here is in jsfiddle: https://jsfiddle.net/armakarma/ykwc3xse/8/
test(){
let array = [4,6,7,1]
let object={}
for (let i = 0; i < array.length; i++){
object[array[i]]={name: 'test', id:30}
if(array[i] > 7){
object[array[i]]={render: true}
} else{
object[array[i]]={render: false}
}
}
console.log(object)
}
Upvotes: 0
Views: 86
Reputation: 1193
In your example, you are adding an attribute/property/key which is object[array[i]]
and will be the same for that loop.
So definitely the if--else block will replace the value with the same key
You can do as follows :
function test() {
let array = [4,6,7,10]
let object={};
for (let i = 0; i < array.length; i++){
let myobj={name: 'test', id:30};
if(array[i] > 7){
myobj.render= true;
} else{
myobj.render= false;
}
object[array[i]] =myobj;
}
console.log(object);
}
test()
Upvotes: 0
Reputation: 1416
Another way, to do what you want is to use a reduce function :
test() {
let array = [4, 6, 7, 1]
const object = array.reduce((acc, value) => {
return { ...acc, [value]: { name: 'test', age: 30, render: value <= 7 } }
}, {})
console.log(object)
}
It's cleaner than use a for loop.
Upvotes: 0
Reputation: 179
In your if/else statements you are overwriting the object keys. Instead you should use spread operator to add properties to existing keys like this:
function test() {
let array = [4, 6, 7, 1];
let object = {};
for (let i = 0; i < array.length; i++) {
object[array[i]] = { name: 'test', id: 30 };
if (array[i] > 7) {
object[array[i]] = { ...object[array[i]], render: true };
} else {
object[array[i]] = { ...object[array[i]], render: false };
}
}
console.log(object);
}
test()
Upvotes: 3
Reputation: 1896
You should use >=
instead of >
, the result you are trying to achieve is never going to be since the condition you are checking is wrong:
array = [4,6,7,1]
object={}
for (let i = 0; i < array.length; i++) {
object[array[i]] = { name: "test", id: 30 };
if (array[i] >= 7) {
object[array[i]].render = true;
} else {
object[array[i]].render = false;
}
}
console.log(object)
Upvotes: 0