javascript - 如何通过拆分字符串将数组转换为对象?




arrays json (5)

我有一个像下面这样的数组:

["gender-m", "age-20", "city-london", "lang-en", "support-home"]

我试图生成一个JSON对象:

{"gender":"m", "age":"20", "city":"london", "lang":"en", "support":"home"}

我能想到的一种解决方案是使用FOR循环来实现它,但是我确信对此有不错的解决方案。 有什么建议,请帮帮我。


使用 Array.reduce 方法

["gender-m", "age-20", "city-london", "lang-en", "support-home"].map(s => s.split('-')).reduce((rs, el) => {rs[el[0]] = el[1]; return rs;}, {});


使用Array.reduce

const arr = ["gender-1", "age-m", "city-london", "lang-en", "support-home"]
arr.reduce((acc, c) => {
    const str = c.split('-')
    return {...acc, [str[0]]: str[1]}
}, {})

您可以使用 Array.reduce 方法来做到这一点

["gender-m", "age-20", "city-london", "lang-en", "support-home"].reduce((rs, el) => {rs[el.split('-')[0]] = el.split('-')[1]; return rs;}, {});


您可以将 Object.fromEntries 与键/值对分开。

var data = ["gender-m", "age-20", "city-london", "lang-en", "support-home"],
    result = Object.fromEntries(data.map(s => s.split('-')));

console.log(result);


由于您最初将此问题标记为“ Lodash”问题,因此以下是基于Lodash的答案:

const arr = ["gender-m", "age-20", "city-london", "lang-en", "support-home"];

const obj = _.chain(arr)
  .map(v => _.split(v, '-'))
  .fromPairs()
  .value();
  
console.log(obj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>





lodash