簡體   English   中英

JavaScript數組推送鍵值

[英]JavaScript Array Push key value

好吧,我在這里有點不對,我已經浪費了一個小時了,所以希望你們其中一個人可以幫助我。

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

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

如何將值推送到var a數組中的每個鍵?

你可以看到我失敗的嘗試,但希望能讓你深入了解我想要實現的目標。

您必須使用括號表示法:

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

結果將是:

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

也許只需要一個具有兩個屬性的對象,而不是一個對象數組:

var x = {};

x[a[i]] = 0;

這將導致x = {left: 0, top: 0}

你可以使用:


要創建對象數組:

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

演示:

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


或者,如果要從數組值創建單個對象:

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

演示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM