Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript push key value into object with index

I have a object variable and i want to push into my object a new { key: "value" } but with a loop and using loop index.

Something like this:

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

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

is there a way to do something like this or add unique key with indexes?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Finally i need something like below:

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

>Solution :

There’s an ES6 thing called "computed properties" which allow regular JS enclosed in [] to form a string key…

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)

Neat, but this creates a throw-away object for each iteration. Skipping the literal with the spread, you can use older JS, more efficiently…

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading