I need help for simple question, to convert this:
{
"data": [{
"data_1": {
"name": "name1",
"value": "value1"
},
"data_2": {
"name": "name2",
"value": "value2"
}
}]
}
To this:
I need help for simple question, to convert this:
{
"data": {
"data_1": {
"name": "name1",
"value": "value1"
},
"data_2": {
"name": "name2",
"value": "value2"
}
}
}
Need to remove '[]'.
Thanks a lot!
CodePudding user response:
If I understand you correctly, it's easy enough. You just need to return 0 element from data
array.
Here is an example in JavaScript:
const original = {
data: [{
data_1: {
name: "name1",
value: "value1"
},
data_2: {
name: "name2",
value: "value2"
}
}]
};
const converted = {
data: original.data[0]
};
CodePudding user response:
Ideally you want to make a deep copy of those inner objects, and create a new object with them. There are many ways to do this but one of the easiest methods is to stringify them (ie the first element of the array), and then parse that string. That way new references are built, and changes to the original data won't have an effect on the new data.
const data={data:[{data_1:{name:"name1",value:"value1"},data_2:{name:"name2",value:"value2"}}]};
// Stringify, and then parse the string
const copy = (o) => JSON.parse(JSON.stringify(o));
// Assemble the new object by copying the part
// for reuse
const out = { data: copy(data.data[0]) };
// Check that changes made to the original object
// are not reflected in the new object
data.data[0].data_1.name = 'bob';
console.log(out);