简体   繁体   中英

How to convert an array into an object in javascript with mapped key-value pairs?

Let's say I have an array like so:

[ 
  {
    field: "firstname",
    value: "John"
  },
  {
    field: "lastname",
    value: "Doe"
  },
  {
    field: "hobbies",
    value: "singing, basketball"
  },
]

Now I want to convert it into an object like so where in the key is the field and the value is the value from the above array:

 const result = { 
      firstname: "John",
      lastname: "Doe",
      hobbies: "Singing, basketball"
    }

You could use Array.prototype.reduce like so:

const arr = [ 
  {
    field: "firstname",
    value: "John"
  },
  {
    field: "lastname",
    value: "Doe"
  }
];

const obj = arr.reduce((acc, val) => { 
  acc[val.field] = val.value; 
  return acc;
}, {});

This would populate the obj object with the values and fields.

You can use .reduce() method to get the desired output:

 const data = [ {field: "firstname", value: "John"}, {field: "lastname", value: "Doe"} ]; const result = data.reduce((r, {field: key, value}) => (r[key] = value, r), {}); console.log(result);

map() the array to Object.values and pass it to Object.fromEntries()

 const arr = [ { field: "firstname", value: "John" }, { field: "lastname", value: "Doe" }, { field: "hobbies", value: "singing, basketball" }, ] const res = Object.fromEntries(arr.map(Object.values)) console.log(res)

The another solution could be using reduce()

 const arr = [ { field: "firstname", value: "John" }, { field: "lastname", value: "Doe" }, { field: "hobbies", value: "singing, basketball" }, ] const res = arr.reduce((ac,a) => (ac[a.field] = a.value,ac),{}) console.log(res)

you can do it with applying simple for loop...

const arr=[ 
        {
         field: "firstname",
         value: "John"
        },
        {
         field: "lastname",
         value: "Doe"
        }
     ];

const obj={} //declare an object

for(let i=0;i<arr.length;i++){
    obj[arr[i].field]=arr[i].value;
  }

alert(obj)  //output : {firstname: "John", lastname: "Doe" }

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