My code is almost correct, but instead of returning a ':' in the Json result as desired, it returns a ','. Is there a way to achieve the desired result without modifying the JSON string like I did with the "replaces"?
I am searching for a more elegant solution that doesn't involve removing the array brackets from the Json expression. Can you help me find a better approach?
// JSON Object
var items = [
{
name: "item 1",
id: 2,
props: {
a: "a prop1",
b: "b prop1",
},
values: [1, 2, 3],
},
{
name: "item 2",
id: 3,
props: {
a: "a prop2",
b: "b prop2",
},
values: [6, 1, 2, 3, 4],
},
{
name: "item 3",
id: 4,
props: {
a: "a prop3",
c: "c prop3",
},
values: [10, 1, 2, 3, 4, 5],
},
];
export function getObject(items) {
var arr = [];
for(var i in items){
arr.push(items[i].name);
arr.push(items[i].props);
}
var myJSON = JSON.stringify(arr).toString();
var test = myJSON.replace("[","{").replace("]","}"); // I couldn't find another way to extract the array data from the array brackets.
var test2 = JSON.stringify(test);
// The current output of test2 is: "{\"item 1\",{\"a\":\"a prop1\",\"b\":\"b prop1\"},\"item 2\",{\"a\":\"a prop2\",\"b\":\"b prop2\"},\"item 3\",{\"a\":\"a prop3\",\"c\":\"c prop3\"}}"
// But the expected output should be: "{\"item 1\":{\"a\":\"a prop1\",\"b\":\"b prop1\"},\"item 2\":{\"a\":\"a prop2\",\"b\":\"b prop2\"},\"item 3\":{\"a\":\"a prop3\",\"c\":\"c prop3\"}}"
return test2;
}