creating a object from array of strings - javascript

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]]

Related

I want to create an object from an array which has subarray also

This is my input:
const arr = [10,20,[40,50,60],70,80,[90,100],111,112];
output what I want:
{10:10,20:20,'array1':{40:40,50:50,60:60},70:70,80:80,'array2':{90:90,100:100},111:111,112:112}
my approach using Array.prototype.reduce(). only handles 1 level nested array.
const arr = [10,20,[40,50,60],70,80,[90,100],111,112];
let count=1;
let a = arr.reduce((acc,curr) => {
if(Array.isArray(curr)){
let b = curr.reduce((acc1,curr1)=> {
acc1[curr1] = curr1;
return acc1
},{})
acc[`array${count}`] = b;
count+=1;
}
else{
acc[curr] = curr;
}
return acc;
},{})
console.log(a)
Since it is an object it necessarily doesn't have to be in the order you have given.
Simply loop through the array, formatting a new object as you go:
let array_count = 1;
let obj = {}
arr.forEach((el) => {
if(Number.isInteger(el)){
obj[el] = el;
} else {
inline_obj = {}
el.forEach((e2) => inline_obj[e2] = e2);
obj[`array${array_count}`] = inline_obj;
array_count += 1;
}
})
Here a recursive solution with reduce(), which also works for deeper nested arrays if you need that.
function foo(array){
let arrCounter=0;
return array.reduce((acc,curr)=>{
if(!Array.isArray(curr)) acc[curr]=curr
else{ arrCounter+=1;
acc[`array${arrCounter}`]=foo(curr)
}
return acc;
},{})
}
const arr = [10,20,[40,50,60],70,80,[90,100],111,112];
console.log(foo(arr));
const deepArr = [10,20,[40,50,60],70,80,[90,100,[40,50,60]],111,112];
console.log(foo(deepArr));

Convert array of strings to object with params and values

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

Convert Array to Object with special case

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

could i use higher function on this?

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)

Dynamic object creation from an array

I want to generate a dynamic object and assign value into it. Following is the code
var chunk = "INTERNATIONALISATION#LANGUAGE#DICTIONARY#EN";
var c = chunk.split('#');
var a = {};
So the output should be like this
a["INTERNATIONALISATION"]["LANGUAGE"]["DICTIONARY"]["EN"] = 10;
Tried looping through array but nothing works for now.Please advise.
Try this:
var chunk = "INTERNATIONALISATION#LANGUAGE#DICTIONARY#EN";
var c = chunk.split('#');
var a = {};
var lastKey = c.pop();
c.reduce((obj, key) => obj[key] = obj[key] || {}, a)[lastKey] = 10;
To make it more convenient you can put it in a function:
const dynamicAssign = (object, stringPath, value) => {
const path = stringPath.split('#');
const lastKey = path.pop();
const target = path.reduce((obj, key) => obj[key] = obj[key] || {}, object);
target[lastKey] = value;
};
const a = {};
dynamicAssign(a, "INTERNATIONALISATION#LANGUAGE#DICTIONARY#EN", 10);

Categories

Resources