how to convert string array of objects to array of objects - javascript

I have an array that I want to convert but I have no idea how to do it
how can i convert this array
const a = ['{/run:true}', '{/sleep:false}'];
in this array
const b = [{'/run':true}, {'/sleep':false}];

Using map and a regular expression:
const a = ['{/run:true}', '{/sleep:false}'];
const b = a.map(s => {
const [_,k,v] = s.match(/\{(.+):(.+)}/);
return {[k]: JSON.parse(v)};
});
console.log(b);
Or other way is to run a sting replacement and JSON.parse
const a = ['{/run:true}', '{/sleep:false}'];
const b = JSON.parse("[" + a.toString().replace(/\{([^:]+)/g, '{"$1"') + "]");
console.log(b);

Created this simple function to do exactly that
const a = ['{/run:true}', '{/sleep:false}'];
// desired output
const b = [{ run: true }, { sleep: false }];
const c = a.map(item => {
const key = item.match(/\w+/)[0];
const value = item.match(/true|false/)[0];
return { [key]: value === 'true' };
});
console.log(c);

const a = ['{/run:true}', '{/sleep:false}'];
const output = a.map(item => {
const normalize = item.replaceAll("{", "").replaceAll("}", "")
const splitedStr = normalize.split(':');
const key = splitedStr[0];
const value = splitedStr[1];
return {[key]: value}
})
console.log(output)

const a = ['{/run:true}', '{/sleep:false}'];
const c = a.map(item => {
return {
['/' + item.split(':')[1].split('{')[0]]: item.split(':')[1].split('}')[0]
};
});
console.log(c);

Related

Check if second array has any string from first array

I am trying to find if second array has any string from the first one.
Not sure what I am doing wrong
const domainAlertList = ["#domain1", "#tomato2", "#carrot3"];
const search = ["test#domain1.com", "test#tomato2.com"];
const myFunc = () => {
return search.some((r) => domainAlertList.includes(r));
};
console.log(myFunc());
It returns false instead of true
const domainAlertList = ["#domain1", "#tomato2", "#carrot3"];
const search = ["test#domain1.com", "test#tomato2.com"];
const myFunc = () => {
return domainAlertList.some((r) => {
return search.some(t => t.includes(r))
});
};
console.log(myFunc());
There are many ways to approach this. One of them could be the indexOf() method.
let str = "test#domain1.com";
str.indexOf('domain1') !== -1 // true
source
You have to map through the second array too like this
const domainAlertList = ["#domain1", "#tomato2", "#carrot3"];
const search = ["test#domain1.com", "test#tomato2.com"];
const myFunc = () => {
return search.some((r) => domainAlertList.some(domain=>{domain.includes(r)});
};
console.log(myFunc());
You can iterate and use array filter function.
const domainAlertList = ["#domain1", "#tomato2", "#carrot3"];
const search = ["test#domain1.com", "test#tomato2.com"];
let r = []
domainAlertList.forEach(i => {
r.push( search.filter(i1 => i1.includes(i)) )
})
newArr = r.map((a) => {
if(a.length != 0) {
return a
}
}).filter((a) => a);
console.log(newArr)
const domainAlertList = ["#domain1", "#domain1", "#carrot3"];
const search = ["test#domain1.com", "test#domain1.com"];
const myFunc = () => {
return domainAlertList.some((domain) =>
search.some((email) => email.includes(domain))
);
};
console.log(myFunc());

Return one element array or empty array best practice in JavaScript

Is there any better way to implement this?
const a = _.get(obj, 'property');
const b = a ? [a] : [];
obj is an object, may or may not have property. If it does, return an array of one element of property, else return an empty array.
const obj = {
prop: "hello"
}
const b = obj.hasOwnProperty("prop") ? [obj.prop] : [];
let obj = {}
console.log("when property is not present: ", obj["property"] || [])
obj = {property: ["hello"]}
console.log("when property is present: ", obj["property"] || [])
You could wrap it into array an filter non-nil value
const a = _.get(obj, 'property');
const b = [a].filter(Boolean);
const a1 = null
const a2 = 1
const res1 = [a1].filter(Boolean)
const res2 = [a2].filter(Boolean)
console.log(res1)
console.log(res2)

merge arrays and convert to JSON string

I have two arrays consist of strings
["25","36","32"] and ["GradeA", "GradeB", "GradeC"]
I want to merge them all together and want to produce JSON string something like this:
{"GradeA" : "25", "GradeB" : "36", "GradeC": "32"}
How do I do this in js?
And for an extra 2 cents I give you the forEach loop version of it. This is taking into consideration that each array is going to be 1 for 1 and in the appropriate order.
var grade = ["GradeA", "GradeB", "GradeC"];
var number = ["25","36","32"];
var obj = {};
grade.forEach(function(x, i){
obj[x] = number[i];
});
console.log(JSON.stringify(obj));
This below code will give your expected output:
var arr1 = [25,36,32] ;
var arr2 = ["GradeA", "GradeB", "GradeC"];
var gradeObj = {};
for(var i = 0;i<arr2.length;i++){
gradeObj[arr2[i]] = arr1[i];
}
console.log(JSON.stringify(gradeObj));
Try like this
var keys =["GradeA", "GradeB", "GradeC"];
var values= ["25","36","32"];
var obj = {};
for(var i=0; i< keys.length; i++){
if(values.length>i+1){
obj[keys[i]] = values[i];
}else{
obj[keys[i]] = null;
}
}
console.log(obj);
Using ES6 reduce:
{
const a = ["25","36","32"];
const b = ["GradeA", "GradeB", "GradeC"];
const merge = (keys, values) => keys.reduce(
(obj, key, i) => (obj[key] = values[i], obj),
{}
);
const json = JSON.stringify(
merge(b, a)
);
console.log(json);
}
with native Reflect API:
{
const a = ["25","36","32"];
const b = ["GradeA", "GradeB", "GradeC"];
const merge = (keys, values) => keys.reduce(
(obj, key, i) => Reflect.set(obj, key, values[i]) && obj,
{}
);
const json = JSON.stringify(
merge(b, a)
);
console.log(json);
}
Using Array#reduce and Object#assign to add a property and it's value to the object on each iteration:
const keys = ["GradeA", "GradeB", "GradeC"];
const values = ["25","36","32"];
const result = keys.reduce((obj, key, i) => Object.assign(obj, { [key]: values[i] }), {});
console.log(result);
Using Array#map, to create a series of object with one property each, then combining them to a single object with Object#assign, and spread:
const keys = ["GradeA", "GradeB", "GradeC"];
const values = ["25","36","32"];
const result = Object.assign(...keys.map((key, i) => ({ [key]: values[i] })));
console.log(result);
Try ES6 Destructuring Assignment :
var obj = {};
var arr1 = ["25","36","32"];
var arr2 = ["GradeA", "GradeB", "GradeC"];
function f([...val1], [...val2]) {
for (var i in val1) {
obj[val1[i]] = val2[i];
}
}
f(arr2, arr1);
console.log(obj);

Initialise an array with same value, x times

If I have:
let a = [1,3,4,5];
how do I dynamically set b to have the same length as a with each entry containing "<", i.e.
Expected result:
b = ["<","<","<","<"];
You can use Array#map:
const a = [1,3,4,5];
const b = a.map(() => "<");
console.log(b);
You can use Array#from:
const a = [1,3,4,5];
const b = Array.from(a, () => "<");
console.log(b);
Or you can use Array#fill:
const a = [1,3,4,5];
const b = new Array(a.length).fill("<");
console.log(b);
Here's a solution:
Array(a.length).fill('<');

Merge 2 arrays of objects setting key from one and value from the other

I have 2 objets a and b defined as the following :
a = {
1:3,
2:5,
3:1,
}
b = {
1:{name:"Bob"},
2:{name:"John"},
3:{name:"Alice"}
}
What I am trying to get is the following object c defined as
c = {
"Bob":3,
"John":5,
"Alice":1
}
So creating an using b[key].name as c[key] and a[key] as value.
What I tried so far is
const mapAandB = (a, b) => {
let finalObject = [];
Object.keys(b).forEach(key => {
return finalOdds.push({ [b[key].name]: a[key] });
});
return finalOdds;
};
but then the result is
c = [
0:{Bob:3},
1:{John: 5},
2:{Alice:1}
]
If you have any suggestion ...
You can use Array#reduce to collect the names and values into an object:
const a = {"1":3,"2":5,"3":1}
const b = {"1":{"name":"Bob"},"2":{"name":"John"},"3":{"name":"Alice"}}
const result = Object.keys(a).reduce((r, key) => {
r[b[key].name] = a[key];
return r;
}, {});
console.log(result);
Or you can use Array#map to create a series of objects, and combine them to one using Object#assign and spread:
const a = {"1":3,"2":5,"3":1}
const b = {"1":{"name":"Bob"},"2":{"name":"John"},"3":{"name":"Alice"}}
const result = Object.assign(...Object.keys(a).map((key) => ({ [b[key].name]: a[key] })));
console.log(result);
Try this solution. If you want to get an object instead of array, just add the result into the Object.assign(...result)
const a = {
1:3,
2:5,
3:1,
}
const b = {
1:{name:"Bob"},
2:{name:"John"},
3:{name:"Alice"}
}
const mapAandB = (a, b) => Object.keys(a).map(key => ({[b[key].name]: a[key]}));
console.log(mapAandB(a,b));

Categories