循环更改对象属性变量

时间:2018-08-09 03:20:27

标签: javascript node.js

var i;
for (i = 0; i < account.feed.data.length; i++) { 
  const rendernew = Object.assign(render ,{account_post_VARIABLE I HERE: `${account.feed.data[i].id}`});
}

我想这样做,以便在循环后更改属性,以便添加新行而不是重写属性的值。任何想法,谢谢!!! :)

预期输出:

{
  account_post_0: "1234"
  account_post_1: "5678"
  account_post_2: "9012"
}

1 个答案:

答案 0 :(得分:1)

应该像在循环中分配每个属性一样简单。

let account={feed:{data:[1,2,3,4,5,6,7,8,9,10].map(x=>({id:x}))}}

let obj={};
for (let i = 0; i < account.feed.data.length; i++) { 
  obj[`account_post_${i}`] = `${account.feed.data[i].id}`
}

console.log(obj)