簡體   English   中英

javascript 將鍵值推入帶索引的 object

[英]javascript push key value into object with index

我有一個 object 變量,我想將一個新的{ key: "value" }推入我的 object 但帶有循環並使用循環索引。

像這樣的東西:

    let headers = {
        product_title: "Product Name",
        action: "Status",
        quantity: "Quantity",
        priority: "Priority",
    };

    for (let i = 0; i < bigger; i++) {
        headers = { ...headers, ...{ 'org_{i}': i } };
    }

有沒有辦法做這樣的事情或添加索引的唯一鍵?

最后我需要下面的東西:

let headers = {
   ...old data
   key_1: "",
   key_2: "",
   key_3: "",
};

ES6 中有一個叫做“計算屬性”的東西,它允許包含在[]中的常規 JS 形成一個字符串鍵......

 let headers = { product_title: "Product Name", action: "Status", quantity: "Quantity", priority: "Priority", }; for (let i = 0; i < 5; i++) { headers = {...headers, ['key_' + i]: i } } console.log(headers)

整潔,但這會為每次迭代創建一個一次性的 object。 跳過帶傳播的文字,您可以更有效地使用舊 JS...

 let headers = { product_title: "Product Name", action: "Status", quantity: "Quantity", priority: "Priority", }; for (let i = 0; i < 5; i++) { headers['key_' + i] = i } console.log(headers)

要將新的鍵值添加到 object 中,您實際上可以使用

headers[key] = value

但是,如果您打算動態設置密鑰,我建議您檢查一下https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

試試下面的東西

const output = [...Array(bigger)].reduce((acc, curr, index) => {
    return ({ ...headers, ...acc, [`org_${index}`]: index })
}, {});

暫無
暫無

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

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