I have JSON of this format
[
{"name":"universityID","value":"454"},
{"name":"grade","value":"88"},
{"name":"date","value":"15-Jan-2016"},
{"name":"address","value":"Washington"}
]
I want my JSON into
{
"universityID":"454",
"grade":"88",
"date":"15-Jan-2016",
"address":"Washington"
}
You just iterate on your array and stuff each attribute into a new object as they come:
var input = [
{"name":"universityID","value":"454"},
{"name":"grade","value":"88"},
{"name":"date","value":"15-Jan-2016"},
{"name":"address","value":"Washington"}
];
var output = {};
input.forEach(function(attr) {
output[attr.name] = attr.value;
});
console.log(output);
EDIT: If universityID needs to be an array:
var input = [
{"name":"universityID","value":"454"},
{"name":"grade","value":"88"},
{"name":"date","value":"15-Jan-2016"},
{"name":"address","value":"Washington"}
];
var output = {};
input.forEach(function(attr) {
if (attr.name == "universityID") {
if (!(attr.name in output)) output[attr.name] = [];
output[attr.name].push(attr.value);
} else {
output[attr.name] = attr.value;
}
});
console.log(output);
Related
I am trying to use the group by function on a JSON array using the inner JSON value as a key as shown below. But unable to read the inner JSON value. Here is my JSON array.
NotificationData = [
{
"eventId":"90989",
"eventTime":"2019-12-11T11:20:53+04:00",
"eventType":"yyyy",
"event":{
"ServiceOrder":{
"externalId":"2434",
"priority":"1"
}
}
},
{
"eventId":"6576",
"eventTime":"2019-12-11T11:20:53+04:00",
"eventType":"yyyy",
"event":{
"ServiceOrder":{
"externalId":"78657",
"priority":"1"
}
}
}
]
GroupBy Logic:
const groupBy = (array, key) => {
return array.reduce((result, currentValue) => {
(result[currentValue[key]] = result[currentValue[key]] || []).push(
currentValue
);
return result;
}, {});
};
const serviceOrdersGroupedByExternalId = groupBy(this.NotificationData, 'event.ServiceOrder.externalId');
//this line of code is not working as
// it is unable to locate the external id value.
Desired output
{ "2434":[{
"eventId":"90989",
"eventTime":"2019-12-11T11:20:53+04:00",
"eventType":"yyyy",
"event":{
"ServiceOrder":{ "priority":"1" }
}
}],
"78657":[{
"eventId":"6576",
"eventTime":"2019-12-11T11:20:53+04:00",
"eventType":"yyyy",
"event":{
"ServiceOrder":{ "priority":"1" }
}
}]
}
Does this solves your purpose?
let group = NotificationData.reduce((r, a) => {
let d = r[a.event.ServiceOrder.externalId] = [...r[a.event.ServiceOrder.externalId] || [], a];
return r;
}, {});
console.log(group);
Try like this:
result = {};
constructor() {
let externalIds = this.NotificationData.flatMap(item => item.event.ServiceOrder.externalId);
externalIds.forEach(id => {
var eventData = this.NotificationData.filter(
x => x.event.ServiceOrder.externalId == id
).map(function(item) {
delete item.event.ServiceOrder.externalId;
return item;
});
this.result[id] = eventData;
});
}
Working Demo
I want to search in json data with multiple levels of array. My search list return names of my objects but just from the first level. How could i do return all my object's names regardless their levels ?
In this example : OST, OST details, Apocalpse Now, Arizona Dream, Dexter
Data
<script type="application/json" id="dataMusic">
{
"name":"Music",
"level":"1",
"size":36184,
"children":[
{
"name":"OST",
"level":"2",
"size":1416,
"children":[
{
"name":"OST details",
"level":"3",
"size":1416,
"children":[
{
"name":"Apocalypse Now",
"size":15
},
{
"name":"Arizona Dream",
"size":19
},
{
"name":"Dexter",
"size":20
}
]
}
]
}
]
}
</script>
Function
var dataMusic = document.getElementById('dataMusic').innerHTML;
var dataTree = JSON.parse(dataMusic);
var optArray = [];
for (var i = 0; i < dataTree.children.length - 1; i++) {
optArray.push(dataTree.children[i].name);
}
optArray = optArray.sort();
I try this method Parsing Nested Objects in a Json using JS without success
Function
var optArray = [], Music, OST, OST details;
for (Music in dataTree) {
for (OST in dataTree[Music]) {
for (OST details in dataTree[Music][OST]) {
if (OST details in optArray) {
optArray[OST details].push(dataTree[Music][OST][OST details].name)
} else {
optArray[OST details] = [dataTree[Music][OST][OST details].name]
}
}
}
}
You must use nested loops
for Music.children.length
for OST.children.length
for OST details.children.length
Edit : Function
var optArray = [], Music, OST, OST_details;
for (Music in dataTree) {
for (OST in dataTree[Music]) {
for (OST_details in dataTree[Music][OST]) {
if (OST_details in optArray) {
optArray[OST_details].push(dataTree[Music][OST][OST_details].name)
} else {
optArray[OST_details] = [dataTree[Music][OST][OST_details].name]
}
}
}
}
I got it
var dataMusic = document.getElementById('dataMusic').innerHTML;
var dataTree = JSON.parse(dataMusic);
var result = [];
function getAll( input, target ) {
function parseData( input, target ) {
$.each( input, function ( index, obj ) {
if ( index == target ) {
result.push( obj );
}
else {
switch ( $.type( obj ).toLowerCase() ) {
case "object":
case "array":
parseData( obj, target );
break;
}
}
});
}
parseData( dataTree, "name" );
result = result.sort();
return result;
}
alert(JSON.stringify( getAll( dataTree, "name" )));
Thanks to this post :
Parsing multi-level json ; Demo
I have multiple json Objects
json1 = [
{'category_id':1,'name':'test1' },
{'category_id':1,'name':'test2' },
{'category_id':1,'name':'test3' },
{'category_id':2,'name':'test2' },
{'category_id':3,'name':'test1' }
];
json2 = [{'category_id':1,'type':'test1'}];
json3 = [
{'category_id':1,'color':'black'},
{'category_id':2,'color':'black'},
{'category_id':3,'color':'white'}
];
I am expecting output like this
final = [
{'category_id':1,'name':'test1','type':'test`','color':'black' },
{'category_id':1,'name':'test2','type':'test`','color':'black' },
{'category_id':1,'name':'test3','type':'test`','color':'black' },
{'category_id':2,'name':'test2','color':'black' },
{'category_id':3,'name':'test1','color':'white' }
];
As i have long json object. Looping is good idea or not ? Does there is any inbuilt function for doing the same.
Using underscore you can achieve it via:
Demo Fiddle
var jsons = [json1, json2, json3];
var final = {};
// merge all data
_.each(jsons, function (jsonArr) {
_.each(jsonArr, function (json) {
final[json.category_id] = _.extend({}, final[json.category_id], json);
});
});
// map it back onto json1
var finalArr = _.map(json1, function (json) {
return final[json.category_id];
});
console.log(finalArr);
Final value of finalArr:
Here is how you can do the same in plain javascript. :)
var final = {};
var jsons = [json1, json2, json3];
for(var i=0;i<jsons.length;i++){
final[i]=jsons[i];
}
Fiddle
EDIT:
Well, you will have to do it programmatically!
I have a JSON string:
var data = {"categories":
[
{"id":1,"parent":0,"name":"Category A","description":"Category description","products":"11","subcategories":[]},
{"id":2,"parent":0,"name":"Category B","description":"Category description","products":"11","subcategories":
[
{"id":6,"parent":2,"name":"Subcategory F","description":"Category description", "products":"2","subcategories":[]},
{"id":7,"parent":2,"name":"Subcategory G","description":"Category description","products":"7","subcategories":[]}
]
},
{"id":3,"parent":0,"name":"Category C","description":"Category description","products":"4","subcategories":
[
{"id":8,"parent":3,"name":"Subcategory H","description":"Category description","products":"8","subcategories":[]}
]
},
{"id":4,"parent":0,"name":"Category D","description":"Category description","products":"45","subcategories":
[
{"id":9,"parent":4,"name":"Subcategory I","description":"Category description","products":"2","subcategories":
[
{"id":10,"parent":9,"name":"Subcategory J","description":"Category description","products":"54","subcategories":[]}
]
}
]
},{"id":5,"parent":0,"name":"Category E","description":"Category description","products":"89","subcategories":[]}
]
};
How can access to the data by id?
For example I need to get this sub_object with id = 10:
var requested = request(data, 10);
function request (data, id) {
var output = {};
...code
output = {"id":10,"parent":9,"name":"Subcategory J","description":"Category description","products":"54","subcategories":[]}
return output;
}
Basically you can do it by a simple recursion: http://jsfiddle.net/99UYU/
var data = {"categories":
[
{"id":1,"parent":0,"name":"Category A","description":"Category description","products":"11","subcategories":[]},
{"id":2,"parent":0,"name":"Category B","description":"Category description","products":"11","subcategories":
[
{"id":6,"parent":2,"name":"Subcategory F","description":"Category description", "products":"2","subcategories":[]},
{"id":7,"parent":2,"name":"Subcategory G","description":"Category description","products":"7","subcategories":[]}
]
},
{"id":3,"parent":0,"name":"Category C","description":"Category description","products":"4","subcategories":
[
{"id":8,"parent":3,"name":"Subcategory H","description":"Category description","products":"8","subcategories":[]}
]
},
{"id":4,"parent":0,"name":"Category D","description":"Category description","products":"45","subcategories":
[
{"id":9,"parent":4,"name":"Subcategory I","description":"Category description","products":"2","subcategories":
[
{"id":10,"parent":9,"name":"Subcategory J","description":"Category description","products":"54","subcategories":[]}
]
}
]
},{"id":5,"parent":0,"name":"Category E","description":"Category description","products":"89","subcategories":[]}
]
};
function recurseArr(arr,id){
for(var i=0;i<arr.length;i++){
var item = arr[i];
if(item.id == id){
return item;
}
var subcategories = item.subcategories;
var ret_val = recurseArr(subcategories,id);
if(ret_val){
return ret_val;
}
}
return null;
}
console.log(recurseArr(data.categories,10));
But you can save your data more usefully because you are using id anyhow - so instead array use objects(map):
var data = {"categories":
{
"1":{"parent":0,"name":"Category A","description":"Category description","products":"11","subcategories":{}},
"2":{"parent":0,"name":"Category B","description":"Category description","products":"11","subcategories":{
"6":{"parent":2,"name":"Subcategory F","description":"Category description", "products":"2","subcategories":{}},
"7":{"parent":2,"name":"Subcategory G","description":"Category description","products":"7","subcategories":{}}
}
}
}
};
then you can access your data more easily.
I am trying to add an object in an array to an item in a JSON object.
The result I am looking for is:
{ "AvailableFacets":[ "color", "sheenlevel" ],
"Selections":[
{ "Facet":"color", "Value":"red" },
{ "Facet":"color", "Value":"blue" }
]
}
but I get the error "TypeError: myJsonObject.Selection.push is not a function" when doing the following:
var testJson = function () {
var myJsonObject = $.parseJSON('{"AvailableFacets":["color", "sheenlevel"]}');
myJsonObject.Selection = "[]";
var newObject1 = $.parseJSON('{"Facet":"color", "Value":"red"}');
var newObject2 = $.parseJSON('{"Facet":"color", "Value":"blue"}');
myJsonObject.Selection.push(newObject1);
return myJsonObject;
};
What am I doing wrong?
"[]" !== []. Did that help? You are using the wrong types. Also you are looking for an output with "Selections" but you are attempting to define "Selection", but I assume that is a typo. This should work:
myJsonObject.Selection = [{"Facet":"color", "Value":"red"},{"Facet":"color", "Value":"blue"}];
But if you wanted to parse a string of JSON as JSON then just change
myJsonObject.Selection = "[]";
to:
myJsonObject.Selection = [];