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