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);
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 obj = {};
let arr = ['val1=123', 'val2=456'];
arr.forEach(i => {
let x = i.split('=');
obj[x[0]] = parseInt(x[1]);
});
console.log(obj);
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 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);
Related
I have a string "101-2000-10-102-2000-15" which I have to map as key: 101 values: {2000, 10}.
With the below code I am able to get the output as 101 => 2000 but I am unable to the one remaining value.
This is the Code:
let myString = "101-2000-10-102-2000-15"
let strArray = myString.match(/[^-]+-[^-]+-[^-]+/g);
console.log(strArray);
let compartmentMap = new Map(strArray.map(x => x.split("-")));
console.log(compartmentMap);
My input: "101-2000-10-102-2000-15"
Desired Output: {101 => {2000,10}, 102 => {2000,15}}
You need to get an array of values as well.
let myString = "101-2000-10-102-2000-15"
let strArray = myString.match(/[^-]+-[^-]+-[^-]+/g);
console.log(strArray);
let compartmentMap = new Map(strArray.map(x => {
const [k, ...v] = x.split("-");
return [k, v];
}));
console.log(Array.from(compartmentMap));
I think I'd be fairly pedestrian about it:
const result = new Map();
const rex = /(\d+)-(\d+)-(\d+)/g;
let match;
while ((match = rex.exec(myString)) !== null) {
result.set(match[1], [match[2], match[3]]);
}
That's assuming you want the 2000, 10 part as an array.
Live Example:
const myString = "101-2000-10-102-2000-15"
const result = new Map();
const rex = /(\d+)-(\d+)-(\d+)/g;
let match;
while ((match = rex.exec(myString)) !== null) {
result.set(match[1], [match[2], match[3]]);
}
console.log([...result.entries()]);
Or with more meaningful names via named capture groups and destructuring:
const result = new Map();
const rex = /(?<key>\d+)-(?<value1>\d+)-(?<value2>\d+)/g;
let match;
while ((match = rex.exec(myString)) !== null) {
const {key, value1, value2} = match.groups;
result.set(key, [value1, value2]);
}
Live Example:
const myString = "101-2000-10-102-2000-15"
const result = new Map();
const rex = /(?<key>\d+)-(?<value1>\d+)-(?<value2>\d+)/g;
let match;
while ((match = rex.exec(myString)) !== null) {
const {key, value1, value2} = match.groups;
result.set(key, [value1, value2]);
}
console.log([...result.entries()]);
Or with the new matchAll and destructuring:
const rex = /(\d+)-(\d+)-(\d+)/g;
const result = new Map(
[...myString.matchAll(rex)].map(
([, key, value1, value2]) => [key, [value1, value2]]
)
);
Live Example:
const myString = "101-2000-10-102-2000-15"
const rex = /(\d+)-(\d+)-(\d+)/g;
const result = new Map(
[...myString.matchAll(rex)].map(
([, key, value1, value2]) => [key, [value1, value2]]
)
);
console.log([...result.entries()]);
One approach would be to just split the string, and then perform a reduce() operation for every three elements:
const s = '101-2000-10-102-2000-15';
const result = s.split('-').reduce((r, v, i, a) =>
i % 3 ? r : {...r, [v]: a.slice(i + 1, i + 3)}, {});
console.log(result);
Slight change to your code, use reduce instead of map.
let myString = "101-2000-10-102-2000-15";
let strArray = myString.match(/[^-]+-[^-]+-[^-]+/g);
console.log(strArray);
let compartmentMap = strArray.reduce((acc, curr) => {
const [a, b, c] = curr.split("-");
return Object.assign(acc, { [a]: [b, c] });
}, {});
console.log(compartmentMap);
Actually, I figured a better which gives out a Map with exact key-value pairs. All I need is to pass a Map and My array to it and it spits out the map with the key-values.
const myString = '101-2000-10-102-2000-15';
let strArray = myString.match(/[^-]+-[^-]+-[^-]+/g);
console.log(strArray);
const compartmentMap = (someMap, someArray) => (someArray.map(x => { console.log(x)
const [a, b, c] = x.split("-");
someMap.set(a, {b,c});
}));
const x = new Map();
compartmentMap(x, strArray);
console.log(x);
how can i turn this array to an object like below
let arr = ["key1:value1","key2,value2"]
to
{
"key1":"value1",
"key2":"value2"
}
Split by either colons or commas, then pass to Object.fromEntries:
const arr = ["key1:value1","key2,value2"];
const obj = Object.fromEntries(
arr.map(str => str.split(/[:,]/))
);
console.log(obj);
Try using reduce:
const arr = ["key1:value1","key2,value2"];
const object = arr.reduce((obj, item) => {
const colon = item.split(':');
if (colon.length === 2) {
obj[colon[0]] = colon[1];
return obj;
}
const comma = item.split(',');
if (comma.length === 2) {
obj[comma[0]] = comma[1];
return obj;
}
return obj;
}, {});
or forEach
const arr = ["key1:value1","key2,value2"];
const object = {};
arr.forEach(item => {
const colon = item.split(':');
if (colon.length === 2) {
obj[colon[0]] = colon[1];
}
const comma = item.split(',');
if (comma.length === 2) {
obj[comma[0]] = comma[1];
}
});
You can try with reduce()
let arr = ["key1:value1","key2,value2"];
var res = arr.reduce((a,c) => {
var k = c.split(/[:,]/)[0];
var v = c.split(/[:,]/)[1];
a[k] = v;
return a
},{});
console.log(res);
My input is like
var resources = ["user-john","user-doe", "students-Milan"];
I am trying to get an output as an object like below,
{
user: ["john", "doe"],
students: ["Milan"]
}
What am i doing wrong
var resources = ["user-john","user-doe", "students-Milan"];
let tempObj = {}
resources.forEach(o => {
let tempArr = o.split("-");
if(tempObj[tempArr[0]]){
tempObj[tempArr[0]] = [...tempArr[1], tempArr[1]]
}else{
tempObj[tempArr[0]] = [tempArr[1]]
}
})
console.log(tempObj)
You could deconstructure the splitted string and build an array as value.
var resources = ["user-john", "user-doe", "students-Milan"],
result = resources.reduce(
(r, s) =>
((key, value) => Object.assign(r, { [key]: [].concat(r[key] || [], value) }))
(...s.split('-')),
{}
);
console.log(result);
You could use reduce method here with an object as a accumulator value.
var data = ["user-john", "user-doe", "students-Milan"];
var result = data.reduce((r, e) => {
let [key, value] = e.split('-');
r[key] = (r[key] || []).concat(value)
return r;
}, {})
console.log(result)
A clean, modern solution:
var resources = ["user-john","user-doe", "students-Milan"];
const output = {}
resources.forEach(item => {
const [key, value] = item.split('-')
output[key] = [...output[key] || [], value]
})
console.log(output)
Here in this part you actually need to :
resources.forEach(o => {
let tempArr = o.split("-");
if(tempObj[tempArr[0]]){
tempObj[tempArr[0]] = [...tempObj[tempArr[0]], tempArr[1]];
}else{
tempObj[tempArr[0]] = [tempArr[1]]
}
})
var resources = ["user-john","user-doe", "students-Milan"];
var tmp = {};
resources.forEach(function(e){
var a = e.split("-");
if(typeof tmp[a[0]] == "undefined"){
tmp[a[0]] = [];
tmp[a[0]].push(a[1]);
}else{
tmp[a[0]].push(a[1]);
}
});
console.log(tmp);
You can use .push method instead [...tempArr[1], tempArr[1]]
var resources = ["user-john","user-doe", "students-Milan"];
let tempObj = {}
resources.forEach(o => {
let tempArr = o.split("-");
if(tempObj[tempArr[0]]){
tempObj[tempArr[0]].push(tempArr[1])
}else{
tempObj[tempArr[0]] = [tempArr[1]]
}
})
console.log(tempObj)
Or you can use the spread syntax on the last state of your array like [...tempObj[tempArr[0]], tempArr[1]] instead [...tempArr[1], tempArr[1]]
I have an array:
let arr = ["a=1", "b=22", "c=11"];
And I want to split the string inside array so it becomes an object later, which will look like:
{a: 1, b: 22, c: 11}
Can I somehow do that
You could split the string an map new objects. Later assign all objects to a single object.
var array = ["a=1", "b=22", "c=11"],
object = Object.assign(
...array.map(s => ((k, v) => ({ [k]: +v }))(...s.split('=')))
);
console.log(object);
you can use array.forEach, so you wont be creating an array instead you will iterate through the array, and you can take each item and split so it will create an array
like item = ["a", "1"], you can assign the key as a to the object which is the first index and value is second index,The value is string so you can convert to number and return it.
let arr = ["a=1", "b=22", "c=11"];
var obj = {}
arr.forEach(o => {
var item = o.split("=");
return obj[item[0]] = Number(item[1])
})
console.log("required obj", obj)
You can use array#map with Object.assign() to create your object. string#split each word on = and generate the object.
let arr = ["a=1", "b=22", "c=11"],
result = Object.assign(...arr.map(word => {
let [key,value] = word.split('=');
return {[key] : +value};
}));
console.log(result);
You can also use array#reduce.
let arr = ["a=1", "b=22", "c=11"],
result = arr.reduce((r,word) => {
let [key,value] = word.split('=');
r[key] = +value;
return r;
}, {});
console.log(result);
Here, try this
let arr = ["a=1", "b=22", "c=11"];
const obj = {}
arr.forEach(i => {
const splitted = i.split('=')
obj[splitted[0]] = splitted[1]
} )
console.log(obj)
this is a code that I want to know if I want to use in some other functions, such ForEach, map, filter, or what else?
is that possible?
const val = 'Mike,Mike#mail.com,male'
const split = val.split(',')
console.log(split) //to check
const newObj = {}
newObj.name = split[0]
newObj.email = split[1]
newObj.gender = split[2]
console.log(newObj)
const val2 = 'name:John,email:John#mail.com'
const split2 = val2.split(',')
console.log(split2) //to check
const newObj2 = {}
for(var i = 0; i < split2.length; i++) {
var data = split2[i].split(':')
newObj2[data[0]] = data[1]
}
console.log(newObj2)
want to make the code more clean and short
const val = 'Mike,Mike#mail.com,male'
const [name, email, gender] = val.split(',')
console.log({name, email, gender})
const val2 = 'name:John,email:John#mail.com'
const splitByColon = term => {
const [key, value] = term.split(':')
return {[key]: value}
}
console.log(
val2
.split(',')
.reduce((acc, term) =>
({...acc, ...splitByColon(term)}), {})
)
Another way could be
const val = 'name:Mike,email:Mike#mail.com,gender:male'
const obj = {}
val.split(',')
.map(prop => prop.split(':'))
.forEach(([key, value]) => {
obj[key] = value
})
console.log(obj)