简体   繁体   English

使用对象键值对的数组值将数组转换为对象

[英]Convert array to object using array values for object key value pairs

I have an array: 我有一个数组:

const arr = [ 'name=Jon', 'weapon=sword', 'hair=shaggy' ]

And I want to convert it to an object like this: 我想将其转换为这样的对象:

const obj = { name: 'Jon', weapon: 'sword', hair: 'shaggy' }

I've tried splitting the array by the = to get the key and value and then mapping the new array and sending those values to an empty object but it doesn't get the right key 我试过用=拆分数组以获取keyvalue ,然后映射新数组并将这些值发送到一个空对象,但它没有获取正确的键

const split = arr.map( el => el.split('=') )
let obj = {};
split.map( el => {
  const key = el[0];
  const val = el[1];
  obj.key = val;
  }
)

obj returns as {key: 'shaggy'} obj返回为{key: 'shaggy'}

Generally, to convert an array into an object, the most appropriate method to use is .reduce : 通常,要将数组转换为对象,最适合使用的方法是.reduce

 const arr = [ 'name=Jon', 'weapon=sword', 'hair=shaggy' ]; const obj = arr.reduce((a, str) => { const [key, val] = str.split('='); a[key] = val; return a; }, {}); console.log(obj); 

You should only use .map when you need to create a new array by carrying out an operation on every item in the old array, which is not the case here. 仅在需要通过对旧数组中的每个项目执行操作来创建新数组时才应使用.map在此情况并非如此。

You can use Object.fromEntries 您可以使用Object.fromEntries

 const arr = [ 'name=Jon', 'weapon=sword', 'hair=shaggy' ] const obj = Object.fromEntries(arr.map(v => v.split('='))) console.log(obj) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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