merge arrays and convert to JSON string - javascript

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

Related

Parsing JavaScript string into 2 arrays

You have a string that is in a following format: "Applejack=A.J.+Applecar,Lemon+Vodka=AlfieCocktail+ Sunset + SexOnTheBeach" and etc.
In Javascript (use .split()), write code to parse a string like this(can be 100000 characters long) that puts the input in 2 different arrays(array key, array values) such that the arrays would llok like the following:
key = ["Applejack", "Lemon+Vodka"]
values = ["A.J+Applecar","AlfieCocktail+Sunset+SexOnTheBeach"]
key = string.split(',').map(x=>x.split("=")[0])
values = string.split(',').map(x=>x.split("=")[1])
You could do something like this
var str = "Applejack=A.J.+Applecar,Lemon+Vodka=AlfieCocktail+ Sunset + SexOnTheBeach";
var first = str.split(',');
var keys = [];
var values = [];
for(let i = 0; i < first.length; i++){
let in_two = first[i].split('=');
keys.push(in_two[0]);
values.push(in_two[1]);
}
console.log(keys);
console.log(values);
You can do it like this:
let str = "Applejack=A.J.+Applecar,Lemon+Vodka=AlfieCocktail+ Sunset + SexOnTheBeach";
let allValues = str.split(','), keys = [], values = [];
allValues.forEach(value => {
const [k,v] = value.split('=');
keys.push(k);
values.push(v);
})
console.log(keys,values);
You can simply use map with reduce.
const str =
"Applejack=A.J.+Applecar,Lemon+Vodka=AlfieCocktail+ Sunset + SexOnTheBeach";
const [keys, values] = str
.split(",")
.map((item) => item.split("="))
.reduce(
(acc, item) => [acc[0].concat(item[0]), acc[1].concat(item[1])],
[[], []]
);
console.log(keys, values);

Remove Duplicate Object from JSON Array

I am trying to remove duplicate JSON Objects from the array in ServiceNow.
Tried below code but it does not remove the duplicate. I want to compare both name & city.
var arr1 = '[{"name":"Pune","city":"India"},{"name":"Pune","city":"India"}]';
var splitlen = JSON.parse(arr1);
alert(splitlen.length);
var uniqueArray = [];
var uniqueJson = {};
for(i=0;i<splitlen.length;i++)
{
if(uniqueArray.indexOf(splitlen[i].name)==-1)
{
uniqueArray.push(splitlen[i]);
}
}
alert(JSON.stringify(uniqueArray));
Expected output :
[{"name":"Pune","city":"India"}]
uniqueArray.indexOf doesn't work because you're comparing objects against strings (splitlen[i].name). Try to use .find() instead:
var arr1 = '[{"name":"Pune","city":"India"},{"name":"Pune","city":"India"}]';
var splitlen = JSON.parse(arr1);
var uniqueArray = [];
var uniqueJson = {};
for(i=0;i<splitlen.length;i++)
{
if(!uniqueArray.find(x => x.name === splitlen[i].name))
{
uniqueArray.push(splitlen[i]);
}
}
console.log(uniqueArray);
or
var arr1 = '[{"name":"Pune","city":"India"},{"name":"Pune","city":"India"}]';
var splitlen = JSON.parse(arr1);
function compare(x){
return x.name === splitlen[i].name;
}
var uniqueArray = [];
var uniqueJson = {};
for(i=0;i<splitlen.length;i++)
{
if(!uniqueArray.find(compare))
{
uniqueArray.push(splitlen[i]);
}
}
console.log(uniqueArray);
you can try this. Also one more thing your array declaration is not right, remove single quotes from array.
var arr1 = [{"name":"Pune","city":"India"},{"name":"Pune","city":"India"}];
function getUniqueListByKey(arr, key) {
return [...new Map(arr.map(item => [item[key], item])).values()]
}
var arr2 = getUniqueListByKey(arr1, "name")
console.log(arr2);
Please try the following example
const arr1 = '[{"name":"Pune","city":"India"},{"name":"Pune","city":"India"}]';
const splitlen = JSON.parse(arr1);
const output = splitlen.reduce((previousValue, currentValue) => {
const { name, city } = currentValue;
const index = previousValue.findIndex(
(entry) => entry.name === name && entry.city === city
);
if (index === -1) {
return [...previousValue, currentValue];
}
return previousValue;
}, []);
console.log(output);
See
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
Put the records in a hashset. If there is collision in the hashset, there is duplicate. This approach is O(n) while comparing all pairs is $O(n^2)$.
I'm trying to get an answer, here's my idea:
Create a function to compare two objects then create a function to get the unique value
function isEquals(obj1, obj2) {
const aProps = Object.getOwnPropertyNames(obj1);
const bProps = Object.getOwnPropertyNames(obj2);
if (aProps.length !== bProps.length) {
return false;
}
for (let j = 0; j < aProps.length; j++) {
const propName = aProps[j];
if (JSON.stringify(obj1[propName]) !== JSON.stringify(obj2[propName])) {
return false;
}
} return true;
}
function getUnique(arr) {
var uniqueArray = [];
for (var item of arr) {
const uniqueItems = arr.filter(i => isEquals(item, i));
if (uniqueItems.length !== 0) {
uniqueArray.push(Object.assign({}, uniqueItems.shift()));
}
arr = arr.filter(i => !isEquals(item, i));
}
return uniqueArray;
}
Hope it helps!

Convert string into key-value pairs in an array

I have a string:
var rrule = "DTSTART=20190514T111500Z;FREQ=DAILY;INTERVAL=1";
I want to convert this string to key-> value pairs in an array.
[
dtstart: 20190514T111500Z,
freq: daily,
interval: 1
]
I know I can take the string and split it based on the semicolon:
var array = rrule.split(";");
... but this leaves me with an array like this:
[
"DTSTART=20190514T111500Z",
"FREQ=DAILY",
"INTERVAL=1"
]
I guess I need another step to map out the keys/values, but I get lost at this point.
Ideally, for the string I want to be able to easily access what dtstarts equals, what interval equals, what other variables equal and so on.
let str = "DTSTART=20190514T111500Z;FREQ=DAILY;INTERVAL=1";
let obj = {};
for (let entry of str.split(";")) {
let pair = entry.split("=");
obj[pair[0]] = pair[1];
}
console.log(obj);
You already know how to split on the ; to get an array, from there you can just aggregate (using reduce) to get an object:
var rrule = "DTSTART=20190514T111500Z;FREQ=DAILY;INTERVAL=1";
var result = rrule.split(";").reduce( (obj,item) => {
let [key,value] = item.split("=");
obj[key] = value;
return obj;
},{});
console.log(result["DTSTART"])
console.log(result["FREQ"])
console.log(result["INTERVAL"])
You were correct to start with split first, this would then return you an array of strings.
To easily convert them, just use map, to return the split the single strings once more, and then return an object based on the property name you would like to give it and it's value
function createKeyValuePairFromString( str ) {
return str.split(';').map( item => {
const splitted = item.split('=');
return { [splitted[0]]: splitted[1] };
});
}
console.log( createKeyValuePairFromString("DTSTART=20190514T111500Z;FREQ=DAILY;INTERVAL=1") );
Use array created and split it again with =
function convertToObject(cookieString) {
const cookieObj = {};
if (!cookieString && typeof cookieString !== 'string') return cookieObj;
const arr = cookieString.split(';');
arr.forEach(record => {
if (record.includes('=')) {
const [key, value] = record.split('=');
cookieObj[key.trim()] = value;
}
});
return cookieObj;
}
You can use it like the code below:
var rrule = "DTSTART=20190514T111500Z;FREQ=DAILY;INTERVAL=1";
let finalObj = {};
rrule.split(';').forEach(i => finalObj[i.split('=')[0]] = i.split('=')[1]);
console.log('finalObj',finalObj);
Here I'm first splitting with ';' so consider the first item to be DTSTART=20190514T111500Z Then on splitting with = I get finalObject['DTSTART'] = 20190514T111500Z
Using forEach()
let str = "DTSTART=20190514T111500Z;FREQ=DAILY;INTERVAL=1";
let obj = {};
let strArr = str.split(';')
strArr.forEach((str) => {
let [key, value] = str.split('=')
obj[key] = value;
});
console.log(obj);
Here's a fairly simple version, returning an object, not an array:
const toObj = str => str
.split (';')
.map ( s => s .split ('=') )
.reduce ( (a, [k, v]) => ({...a, [k]: v}), {} )
let str = "DTSTART=20190514T111500Z;FREQ=DAILY;INTERVAL=1";
console.log (
toObj(str)
)
One of the reasons I like the library is that we can write this sort of logic more simply. In Ramda (disclaimer: I'm one of the authors), it might look like this:
const toObj = pipe ( split (';'), map (split ('=') ), fromPairs)
let str = "DTSTART=20190514T111500Z;FREQ=DAILY;INTERVAL=1";
console.log (
toObj(str)
)
<script src="https://bundle.run/ramda#0.26.1"></script><script>
const {pipe, split, map, fromPairs} = ramda; </script>
var str = "DTSTART=20190514T111500Z;FREQ=DAILY;INTERVAL=1";
// string splitting rule
const rule = (string, delimiter) => string.split(delimiter);
const result = rule(str, ';').reduce((acc, s) => {
const [key, value] = rule(s, '=');
acc[key] = value;
return acc;
}, {});
console.log(result);

Convert String Into Delimited Object Key

I am trying to convert a string into a delimited object key but I need some assistance on how to iterate over the length of the array and join accordingly.
SET('my.delimited.string.of.unknown.length')
const SET = key => (state, val) => {
if(key.indexOf('.') !== -1) {
let array = key.split(".")
for (var i = 0; i < array.length; i++) {
// what should I do here?
}
// desired output based on array length
// state[ array[0] ][ array[1] ] = val
// state.my.delimited.string.of.unknown.length = val
}
}
One of those very rare usecases for reduce:
const keys = key.split(".");
const prop = keys.pop();
keys.reduce((acc, key) => acc[key], state)[prop] = val;
For sure that could also be done with a for loop:
let array = key.split("."), acc = state;
for (var i = 0; i < array.length - 1; i++) {
acc = acc[ array[i] ];
}
acc[ array.pop() ] = val;
For setting a value, you could split the path and reduce the path by walking the given object. If no object exist, create a new property with the name. Later assign the value.
function setValue(object, path, value) {
var keys = path.split('.'),
last = keys.pop();
keys.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value;
}
var test = {};
setValue(test, "first.deep.property", 1);
setValue(test, "and.another.deep.property", 20);
console.log(test);
You could also do this with a single Array.reduce:
const makeObject = (arr, val, obj={}) => {
arr.split('.').reduce((r,c,i,a) => r[c] = i == a.length-1 ? val : {}, obj)
return obj
}
console.log(makeObject("first.deep.property", 1))
console.log(makeObject("and.another.deep.property", 20))

How to convert an array of objects to object with key value pairs

I want to convert an array of objects to object with key value pairs in javascript.
var arr=[{"name1":"value1"},{"name2":"value2"},...}];
How can i convert it to an object such as
{"name1":"value1","name2":"value2",...}
I want it to be supported in majority of browsers.
You could use Object.assign and a spread syntax ... for creating a single object with the given array with objects.
var array = [{ name1: "value1" }, { name2: "value2" }],
object = Object.assign({}, ...array);
console.log(object);
You could run a reduce over the array and return a new object. But it is important to remember that if properties are the same they will be overwritten.
const newObject = array.reduce((current, next) => {
return { ...current, ...next};
}, {})
If you are using es5 and not es6:
var newObject = array.reduce(function(current, next){
return Object.assign({}, current, next);
}, {})
With modern JS (YMMV):
Split each object into entries
Aggregate all entries into one object
const arr = [{name1:"value1"}, {name2:"value2"}, {a:1,b:2}];
const obj = Object.fromEntries(arr.flatMap(Object.entries));
console.log(obj);
Try this simple logic
var arr=[{"name1":"value1"},{"name2":"value2"}];
var obj = {}; //create the empty output object
arr.forEach( function(item){
var key = Object.keys(item)[0]; //take the first key from every object in the array
obj[ key ] = item [ key ]; //assign the key and value to output obj
});
console.log( obj );
use with Array#forEach and Object.keys
var arr = [{"name1": "value1"},{"name2": "value2"}];
var obj = {};
arr.map(k => Object.keys(k).forEach(a => obj[a] = k[a]))
console.log(obj)
Using for...in loop :
var arr=[{"name1":"value1"},{"name2":"value2"}];
var obj = {};
for (var i in arr) {
obj[Object.keys(arr[i])] = arr[i][Object.keys(arr[i])];
}
console.log(obj);
Using Array.map() method with ES6 :
var arr=[{"name1":"value1"},{"name2":"value2"}];
var obj = {};
arr.map(item => obj[Object.keys(item)] = item[Object.keys(item)]);
console.log(obj);
Using Object.assign() method with ES6 spreaqd(...) assignment :
let arr=[{"name1":"value1"},{"name2":"value2"}];
let obj = Object.assign({}, ...arr);
console.log(obj);
Supposing that you have myObject and myArray
myObject = {};
myArray = [
{itemOneKey: 'itemOneValue', itemTwoKey: 'itemTwoValue'},
{itemThreeKey: 'itemThreeValue'}
];
simply try this:
myArray.map(obj => {
Object.keys(obj).map(key => myObject[key] = obj[key])
});
const myObject = {};
const myArray = [
{itemOneKey: 'itemOneValue', itemTwoKey: 'itemTwoValue'},
{itemThreeKey: 'itemThreeValue'}
];
myArray.map(obj => {
Object.keys(obj).map(key => myObject[key] = obj[key])
});
console.log(myObject);

Categories