javascript - without - How can I convert an array to an object by splitting strings?
string to array php (5)
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];
}
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.
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);
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;}, {});
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]}
}, {})
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);