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 |7 Answers
Reset to default 14You 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;}, {});
Array.reduce
– bamtheboozle Commented Oct 22, 2019 at 15:56