简体   繁体   中英

I want to get an associative array form a JavaScript object list

I have a JavaScript object like

<pre>
{
 1:{taxCalculation: 39.95, taxId: "3"},
 2:{taxCalculation: 10,    taxId: "3"},
 5:{taxCalculation: 0.48,  taxId: "2"}
}
</pre>

I want to create an associative array from the object like below

<pre>
 [
  1:{taxCalculation: 39.95, taxId: "3"},
  2:{taxCalculation: 10,    taxId: "3"},
  5:{taxCalculation: 0.48,  taxId: "2"}
 ]
</pre>

Lets say your object is called myObject . You can simply create an array in Javascript like below.

let myArray = [];

Object.keys(myObject).forEach((key, index) => {
  myArray[key] = myObject[key];
});

Your new Array myArray should give you what you want.

You can try the following using ES6 syntax

 var obj = { 1: {taxCalculation: 39.95, taxId: "3"}, 2: {taxCalculation: 10, taxId: "3"}, 5: {taxCalculation: 0.48, taxId: "2"} } let answer = [...Object.values(obj)] console.log(answer) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM