Reputation: 149
I have a set of array like this : [["Sarah"],["Jamie"],["B"],["148"]]
and I want to convert this into JSON string with specific element for each vaues. For example,
{ "name":"Sarah", "grade":"148", "School":"B"...}
How should I proceed? I tried to toString the array then bind with this element but it doesn't work out well..
Original Json
"Data":{
"Table":[
{
"Name":[
"Jamie"
],
"School":[
"A"
],
"grade":[
"99"
]
},
{
"Name":[
"Mike"
],
"School":[
"B"
],
"grade":[
"148"
]
}
]
}
}
Upvotes: 1
Views: 4649
Reputation: 1
let newDataArray = this.data.Data.Table.reduce(function(arr, obj) {
let newObj = {};
for (let key in obj) {
newObj[key] = obj[key][0]
}
arr.push(newObj);
return arr;
}, []
);
newData =JSON.stringify(newDataArray);
JSON.stringify(newDataArray)
array from tymeJV 's code snippet will give you the JSON string as follows.
[{"Name":"Jamie","School":"A","grade":"99"},{"Name":"Mike","School":"B","grade":"148"}]
Demo: http://plnkr.co/edit/wPhVTOFhRgERLXKCuoYl?p=preview
Upvotes: 0
Reputation: 272
You can try with the simple forEach
var data = {"Data": {"Table": [{"Name": ["Jamie"],"School": ["A"],"grade": ["99"]},{"Name": ["Mike"],"School": ["B"],"grade": ["148"]}]}};
var items = [];
data['Data']['Table'].forEach(function(item){
items.push({name: item.Name[0], grade: item.grade[0], school: item.School[0]});
});
console.log(JSON.stringify(items));
Upvotes: 1
Reputation: 104775
You can use reduce
to do this!
let newData = data.Data.Table.reduce(function(arr, obj) {
let newObj = {};
for (let key in obj) {
newObj[key] = obj[key][0]
}
arr.push(newObj);
return arr;
}, [])
Demo: https://jsfiddle.net/500eo2gp/
Upvotes: 0