这是一个奇怪的想法,但让我解释一下。我有这个:
client({
Action: 'UrlInfo',
'UrlInfo.Shared.ResponseGroup': 'Rank',
'UrlInfo.1.Url': 'lupomontero.com',
'UrlInfo.2.Url': 'yahoo.com',
'UrlInfo.3.Url': 'weibo.com',
'UrlInfo.4.Url': 'github.com',
'UrlInfo.5.Url': 'monono.org'
},
所以目前它已被硬编码。我想创建UrlInfo"数组"。我希望这能解释我想做的事情:
for (let i = 0; i < websites.length; i++) {
var data = {'UrlInfo$'+i + 1 + 'Url':websites[i]};
}
这不起作用。我该如何让它发挥作用?
答案 0 :(得分:1)
首先创建结果对象,然后在for循环中分配每个网站。
试试这样:
const websites = [
'lupomontero.com',
'yahoo.com',
'weibo.com',
'github.com',
'monono.org',
];
const ret = {};
for (let i = 0; i < websites.length; i++) {
ret['UrlInfo.' + (i + 1) + '.Url'] = websites[i];
}
console.log(ret);
答案 1 :(得分:1)
您可以使用简单的for
循环尝试此操作:
const websites=["lupomontero.com","yahoo.com","weibo.com","github.com","monono.org"];
const data = {};
for (let i = 0; i < websites.length; i++) {
data['UrlInfo.' + (i + 1) + '.Url'] = websites[i] || '';
}
console.log(data)
&#13;
或者,使用reduce()
const websites=["lupomontero.com","yahoo.com","weibo.com","github.com","monono.org"];
const data = websites.reduce((o, a, i) => ({ ...o, ['UrlInfo.' + (i + 1) + '.Url']: websites[i]}), {})
console.log(data)
&#13;
答案 2 :(得分:0)
使用ES6功能,您应该能够使用reduce
组合这样的对象,假设websites
是一个数组:
const data = websites.reduce((accumulator, website, currentIndex) => {
accumulator[`UrlInfo.${currentIndex + 1}.Url`] = website
return accumulator
}, {})
${currentIndex}
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals