简体   繁体   English

javascript ecma6将数组项转换为键值对的对象

[英]javascript ecma6 convert array items into an object of key value pairs

I want to convert an array with some operations into an object of key and value. 我想将具有某些操作的数组转换为键和值的对象。 Here is my attempt: 这是我的尝试:

const config = [ 'key1=value1', 'key2=value2' ];

const configObject = config.map(c => {
  var key = c.split('=')[0];
  var value = c.split('=')[1];
  return  {key:value}
})

console.log('configObject', configObject) // [ { key: 'value1' }, { key: 'value2' } ]

I want to obtain an object of key value, rather than an array without any kind of old school for loop . 我想获得一个具有键值的对象,而不是一个没有任何旧式for循环的数组。 like this: 像这样:

{ key: 'value1' , key: 'value2' }

Use the function reduce . 使用功能reduce

 const config = [ 'key1=value1', 'key2=value2' ]; const configObject = config.reduce((a, c) => { var [key, value] = c.split('='); return { ...a, ...{[key]: value} }; }, {}); console.log(configObject); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

You should use .reduce instead 您应该改用.reduce

 const config = [ 'key1=value1', 'key2=value2' ]; var data = config.reduce( (acc, el) => { acc[el.split("=")[0]] = el.split("=")[1]; return acc; }, {} ); console.log(data); 

You're almost there. 你快到了。 The idiom you're looking for is Object.assign(...array-of-objects) : 您要查找的惯用法是Object.assign(...array-of-objects)

 config = [ 'key1=value1', 'key2=value2' ]; configObject = Object.assign(...config.map(c => { var key = c.split('=')[0]; var value = c.split('=')[1]; return {[key]:value} })) console.log(configObject) 

Also note, it's [key]: , not just key: . 另请注意,它是[key]:而不仅仅是key:

A more concise but perhaps less readable option: 一个更简洁但可读性较低的选项:

configObject = Object.assign(...config
     .map(c => c.split('='))
     .map(([k, v]) => ({[k]: v})));

You could map the splitted key/value pairs in new object and collect all with Object.assign in a single object. 您可以将拆分的键/值对映射到新对象中,并使用Object.assign收集所有对象。

 var array = ['key1=value1', 'key2=value2'], object = Object.assign(...array.map(s => (([k, v]) => ({ [k]: v }))(s.split('=')))); console.log(object); 

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

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