JavaScript 数组推送键值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7813374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:41:57  来源:igfitidea点击:

JavaScript Array Push key value

javascriptarrayspush

提问by daryl

Ok, I'm going a little wrong here and I've already wasted an hour with this so hopefully one of you guys can help me.

好的,我在这里有点错误,我已经浪费了一个小时,所以希望你们中的一个人可以帮助我。

var a = ['left','top'],
    x = [];

for(i=0;i<a.length;i++) {
    x.push({
        a[i] : 0
    });
}

How do I go about pushing a value to each of the keys inside the var aarray?

如何将值推送到var a数组内的每个键?

You can see my failed attempted but hopefully that will give you an insight into what I'm trying to achieve.

你可以看到我失败的尝试,但希望这能让你深入了解我正在努力实现的目标。

回答by Felix Kling

You have to use bracket notation:

您必须使用括号表示法:

var obj = {};
obj[a[i]] = 0;
x.push(obj);

The result will be:

结果将是:

x = [{left: 0}, {top: 0}];

Maybe instead of an array of objects, you just want one object with two properties:

也许您只需要一个具有两个属性的对象,而不是一组对象:

var x = {};

and

x[a[i]] = 0;

This will result in x = {left: 0, top: 0}.

这将导致x = {left: 0, top: 0}.

回答by Mohammad Usman

You may use:

您可以使用:



To create array of objects:

创建对象数组:

var source = ['left', 'top'];
const result = source.map(arrValue => ({[arrValue]: 0}));

Demo:

演示:

var source = ['left', 'top'];

const result = source.map(value => ({[value]: 0}));

console.log(result);



Or if you wants to create a single object from values of arrays:

或者,如果您想从数组的值创建单个对象:

var source = ['left', 'top'];
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});

Demo:

演示:

var source = ['left', 'top'];

const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});

console.log(result);