我有一个如下数组:
["gender-m", "age-20", "city-london", "lang-en", "support-home"]
我尝试生成JSON对象:
{"gender":"m", "age":"20", "city":"london", "lang":"en", "support":"home"}
我能想到的一种解决方案是使用FOR循环来实现,但是我确信有很好的解决方案。有任何建议,请帮助我。
答案 0 :(得分:12)
您可以将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);
答案 1 :(得分:1)
使用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]}
}, {})
答案 2 :(得分:1)
我认为没有一种优雅的方法,因为您使用“-”符号来分隔键和值。因此,最好的方法是:
let element = {};
array.forEach(item => {
result = item.split("-");
element[result[0]] = result[1];
}
答案 3 :(得分:1)
可以使用拆分和地图来解决,对于数组内部的每个项目,将-替换为::变成键值,然后将这些值分配给要返回的对象。
var arrayObject = ["gender-m", "age-20", "city-london", "lang-en", "support-home"];
var objectResulted ={};
arrayObject.map(
function(item){
var splitedValue = item.split('-');
objectResulted [splitedValue[0]]= splitedValue[1]
});
console.log(objectResulted);
答案 4 :(得分:1)
由于您最初将其标记为“ 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>
答案 5 :(得分:1)
使用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;}, {});
答案 6 :(得分: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;}, {});