'Convert React/javascript string array of objects to array of objects
This seems like a trivial issues but I can't get it working properly. I'm fairly new to JS/React so that is working against me also.
This is the response I get back (it's a TS object type but is actually a plain string so I can't iterate it and it just isn't useful):
[{"answer": "Within 2 weeks", "question": "Moving/Purchase date"}, {"answer": "2 bedrooms", "question": "Bedrooms (minimum) ?"}]
How can I convert that into an array of objects so I can iterate through them? Like so;
[
0: { "answer": "Yes", "question": "Are you sure?" },
1: { "answer": "False", "question": "Do you hold a valid passport?" }
]
I've tried doing JSON.parse and creating a Map but it doesn't provide the expected output. Any help would be greatly appreciated. Thanks all! :)
Solution 1:[1]
I managed to sort it using the following:
const arrayObj = JSON.parse(results as unknown as string);
Solution 2:[2]
Have you considered eval?
Of course it's risky to use if your system allows arbitrary Javascript code to be executed, but if you're sure running code from a string, here converting the code (the array inside it if it were to be a line of code) in the string to an array object isn't harmful in your environment, use it.
let str = '[{"answer": "Within 2 weeks", "question": "Moving/Purchase date"}, {"answer": "2 bedrooms", "question": "Bedrooms (minimum) ?"}]';
let obj = eval(str);
console.log(obj, typeof(obj));
for (const element of obj){
console.log(element);
} ;
I've used JSON.parse and it seems to be working too (recommended option):
let str = '[{"answer": "Within 2 weeks", "question": "Moving/Purchase date"}, {"answer": "2 bedrooms", "question": "Bedrooms (minimum) ?"}]';
let obj = JSON.parse(str);
console.log(obj, typeof(obj));
for (const element of obj){
console.log(element);
} ;
Solution 3:[3]
pass your array str in this line you get your output in obj. like this const obj = Object.assign({}, str);
Solution 4:[4]
If you want to wrap it inside another object with indices being the keys then you can use reduce.
const list = [{
"answer": "Within 2 weeks",
"question": "Moving/Purchase date"
}, {
"answer": "2 bedrooms",
"question": "Bedrooms (minimum) ?"
}]
const newList = list.reduce((acc, x, i) => [...acc, {
[i]: x
}], []);
console.log(newList)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | user.io |
Solution 2 | |
Solution 3 | user18889214 |
Solution 4 | Eugen Sunic |