最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I convert an array to an object by splitting strings? - Stack Overflow

programmeradmin3浏览0评论

I have an array like below:

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

I tried to generate a JSON object:

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

One solution I can think of is using FOR loop to make it, but I am sure there are elegant solutions for this. Any suggestions, please help me.

I have an array like below:

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

I tried to generate a JSON object:

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

One solution I can think of is using FOR loop to make it, but I am sure there are elegant solutions for this. Any suggestions, please help me.

Share Improve this question edited Oct 22, 2019 at 16:03 isherwood 61.1k16 gold badges120 silver badges168 bronze badges asked Oct 22, 2019 at 15:54 franco phongfranco phong 2,2194 gold badges28 silver badges48 bronze badges 1
  • could use Array.reduce – bamtheboozle Commented Oct 22, 2019 at 15:56
Add a comment  | 

7 Answers 7

Reset to default 14

You could take Object.fromEntries with the splitted key/value pairs.

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

console.log(result);

I don't think there is an elegant way because you use the "-" sign to separate key and value. So, the best way would be:

let element = {};
array.forEach(item => {
result = item.split("-"); 
element[result[0]] = result[1];
}

Use 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]}
}, {})

It can be solve with split and a map, foreach item inside of the array replace the - with : using the split it will be turned into a key value, then assign those values to the object you want to return.

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);

Since you originally tagged this as a "Lodash" question, here is a Lodash-based answer:

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>

Use Array.reduce method

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

You can use Array.reduce method to do that

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

发布评论

评论列表(0)

  1. 暂无评论