Reputation: 59
I have an array with multiple objects.So how to make a new object by splitting the objects.
Here is how i am doing manually. How can I achieve it dynamically.
var a ='["{\\"Transfer_Notes__c\\":{\\"filterType\\":\\"text\\",\\"type\\":\\"contains\\",\\"filter\\":\\"abc\\"}}","{\\"IQ_Score__c\\":{\\"filterType\\":\\"number\\",\\"type\\":\\"equals\\",\\"filter\\":null,\\"filterTo\\":null}}"]';
var c = {};
c= JSON.parse(a);
const obj = Object.assign({}, JSON.parse(c[0]),JSON.parse(c[1]));
console.log(obj)
I tried several ways. Please help!
Upvotes: 3
Views: 201
Reputation: 50974
You could use a reviver function with JSON.parse()
to specify that the array values should also be parsed. Then you can spread the parsed objects from the array into a resulting object using Object.assign()
:
var a ='["{\\"Transfer_Notes__c\\":{\\"filterType\\":\\"text\\",\\"type\\":\\"contains\\",\\"filter\\":\\"abc\\"}}","{\\"IQ_Score__c\\":{\\"filterType\\":\\"number\\",\\"type\\":\\"equals\\",\\"filter\\":null,\\"filterTo\\":null}}"]';
const parsed = JSON.parse(a, (key, val) => key ? JSON.parse(val) : val);
const c = Object.assign({}, ...parsed);
console.log(c);
Upvotes: 1
Reputation: 59
var a ='["{\\"Transfer_Notes__c\\":{\\"filterType\\":\\"text\\",\\"type\\":\\"contains\\",\\"filter\\":\\"abc\\"}}","{\\"IQ_Score__c\\":{\\"filterType\\":\\"number\\",\\"type\\":\\"equals\\",\\"filter\\":null,\\"filterTo\\":null}}"]';
var c = {};
c= JSON.parse(a);
const A ={};
var obj = {};
for(var i=0;i<c.length;i++){
obj = Object.assign(A, JSON.parse(c[i]),);
}
console.log(obj)
Please suggest if there is any alternative way; Suggest me if i am doing wrong
Upvotes: -1
Reputation: 1650
var a ='["{\\"Transfer_Notes__c\\":{\\"filterType\\":\\"text\\",\\"type\\":\\"contains\\",\\"filter\\":\\"abc\\"}}","{\\"IQ_Score__c\\":{\\"filterType\\":\\"number\\",\\"type\\":\\"equals\\",\\"filter\\":null,\\"filterTo\\":null}}"]';
var c = JSON.parse(a);
const obj = c.reduce((obj, c) => Object.assign(obj, JSON.parse(c)), {});
console.log(obj)
Upvotes: 4