I am having an array
myArray= ["{ depth: 1, display: 'X' }", "{ depth: 2, display: 'X.X' }", "{ depth: 3, display: 'X.X.X' }", "{ depth: 4, display: 'X.X.X.X' }", "{ depth: 5, display: 'X.X.X.X.X' }", "{ depth: 6, display: 'X.X.X.X.X.X' }"]
I need my output array like this
expectedResult = [{ depth: 1, display: 'X' }, { depth: 2, display: 'X.X' }, { depth: 3, display: 'X.X.X' }, { depth: 4, display: 'X.X.X.X' }, { depth: 5, display: 'X.X.X.X.X' }, { depth: 6, display: 'X.X.X.X.X.X' }]
I tried with this
myArray.map(item => {
const container = {};
container[item.depth] = item.display;
console.log(JSON.stringify(container));
return container;
})
But it gives undefined. How can I solve this?
JSON.parse(), notJSON.stringify. That being said, it's not going to work because the strings in the array are not valid JSON. You need to amend them so that they are valid JSON, however if you can edit the response then it'd make more sense to just not use JSON at all.var x = { depth:1, display:"x" };JSON.stringify(x)gives'{"depth":1,"display":"x"}'JSON.parse()or RegEx, you can do it witharr.map(item => (new Function('return ' + item))() ), which is flexible to any object, which is in a string format that JavaScript can parse.