I have next array with strings:
['val1=123','val2=456']
How I can split it to object with params and values?
{
val1: 123,
val2: 456,
}
I have next array with strings:
['val1=123','val2=456']
How I can split it to object with params and values?
{
val1: 123,
val2: 456,
}
const recordStrings = ['val1=123', 'val2=456']
const record = Object.fromEntries(
recordStrings.map(str => str.split('='))
)
console.log(record)
Explanation:
recordStrings.map(str => str.split('='))
returns [[val1, 123], [val2, 456]]
.
Object.fromEntries(entries)
creates an object from an array containing [key, value]
tuples.
You can try with reduce method, it's really helpful to convert an array to any others data type like an object, string, number.
const arr = ['val1=123','val2=456'];
const items = arr.reduce((total, item) => {
const [key, value] = item.split('=');
if (key) {
total[key] = value
}
return total;
}, {})
console.log(items);
let arr = ['val1=123', 'val2=456']
let object = {}
for (let i = 0; i < arr.length; i++) {
var split = arr[i].split("=")
object[split[0]] = split[1]
}
console.log(object); // { val1: '123', val2: '456' }
let obj = {};
let arr = ['val1=123', 'val2=456'];
arr.forEach(i => {
let x = i.split('=');
obj[x[0]] = parseInt(x[1]);
});
console.log(obj);
Split the strings in the array and convert the array to an object:
const res = ['val1=123','val2=456'];
const result = Object.fromEntries(res.map(x => {
const [l, r] = x.split('=');
return [l, +r];
}));
console.log(result);
let arr = ['val1=123','val2=456'];
arr.forEach(str => {
let arrStr = str.split('=');
eval(arrStr[0] + '= ' + arrStr[1] + ';');
})
console.log(val1, val2);
OR
let arr = ['val1=123','val2=456'];
arr.forEach(str => {
let arrStr = str.split('=');
window[arrStr[0]] = arrStr[1];
})
console.log(val1, val2);