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.
Related
function myFunction(input_data)
{
const myJSON = JSON.stringify(input_data);
const myJSON1 = JSON.parse(myJSON);
const data = myJSON1["data"];
const input = JSON.stringify(myJSON1.data);
var result="";
//return typeof input;
for(var i=1;i<input.length-1;i++){
//Logger.log(input[i]);
result += input[i];
}
Logger.log(result);
const obj_result = JSON.parse(result);
const code_status = obj_result.code;
Logger.log(code_status);
result_details= JSON.stringify(obj_result.details);
obj_result_details = JSON.parse(result_details);
Logger.log(obj_result_details.id);
return obj_result_details.id;
}
input_data = {"data":[{"code":"SUCCESS","details":{"Modified_Time":"2022-08-
12T18:30:42+05:30","Modified_By":{"name":"",
"id":"8"},"Created_Time":"2022-08-
12T18:30:42+05:30","id":"87956000","Created_By":{"name":"dev"
,"id":"8"}},"message":"record added","status":"success"}]};
Logger.log(myFunction(input_data));
Error: TypeError: cann't read property length at line no 9.
(this error I am getting in sheet but not in script editor).
As a guess. If you meant to get an array of IDs from the input_data it can be done this way:
var input_data = {
data: [
{
code: "SUCCESS",
details: {
Modified_Time: "2022-08-12T18:30:42+05:30",
Modified_By: { name: "", id: "8" },
Created_Time: "2022-08-12T18:30:42+05:30",
id: "87956000",
Created_By: { name: "dev", id: "8" },
},
message: "record added",
status: "success",
},
],
};
function myFunction(input_data) {
return input_data.data.map(x => x.details.id);
}
console.log(myFunction(input_data)); // output: [ '87956000' ]
I got parsed data object. The data is retuned by backend as JSON and has been parsed as data object in react-native client.
{
"level1-key1": "value1",
"level1-key2": "value2",
"level1-key3": "value3",
"level1-key4":{
"level2-k1": "val1",
"level2-k2": {
"level3-k1": "v1",
"level3-k2": "v2",
"level3-k3": "v3"
}
}
}
I would like to get different level keys as an array of strings, i.e. I want to get level 2 keys, which are ["level2-k1", "level2-k2"].
I want to get level 3 keys, which are
["level3-k1", "level3-k2", "level3-k3"]
How achieve it?
I think it should solve your problem
const data = {
'level1-key1': 'value1',
'level1-key2': 'value2',
'level1-key3': 'value3',
'level1-key4': {
'level2-k1': 'val1',
'level2-k2': {
'level3-k1': 'v1',
'level3-k2': 'v2',
'level3-k3': 'v3',
},
},
};
const isObject = (v) => typeof v === 'object' && v != null;
const getAllKeysByLevel = (data, level) => {
let levelObjects = [data];
for (let i = 0; i < level; i += 1) {
levelObjects = levelObjects.flatMap((item) =>
isObject(item) ? Object.values(item) : [],
);
}
return levelObjects.flatMap((item) =>
isObject(item) ? Object.keys(item) : [],
);
};
const level1 = getAllKeysByLevel(data, 0);
const level2 = getAllKeysByLevel(data, 1);
const level3 = getAllKeysByLevel(data, 2);
console.log(' --- xdebug ', {
level1,
level2,
level3,
});
/*
--- xdebug {
level1: [ 'level1-key1', 'level1-key2', 'level1-key3', 'level1-key4' ],
level2: [ 'level2-k1', 'level2-k2' ],
level3: [ 'level3-k1', 'level3-k2', 'level3-k3' ]
}
*/
This should do the work, finding out the leaf nodes and check if it is an object and repeat it till the end.
const data = {
"level1-key1": "value1",
"level1-key2": "value2",
"level1-key3": "value3",
"level1-key4":{
"level2-k1": "val1",
"level2-k2": {
"level3-k1": "v1",
"level3-k2": "v2",
"level3-k3": "v3"
}
}
}
function findLevels(data){
let counter = 1;
let final = {};
getKeys(data)
function getKeys(obj){
let k = Object.keys(obj);
final[counter] = k;
// scan if there is any object
for(let i = 0; i < k.length; i++){
if(typeof obj[k[i]] === "object"){
counter += 1;
getKeys(obj[k[i]])
}
}
}
return final;
}
const result = findLevels(data);
console.log(result)
I have a problem converting my JSON to desired format. I have something like this:
{
"one:apple": "5",
"one:orange": "10",
"two:apple": "6",
"two:orange": "11"
}
and I would like to get:
[
["one","5","10"],
["two","6","11"]
]
Any help appreciated...
Assuming that your JSON is:
{
"one:apple": "5",
"one:orange": "10",
"two:apple": "6",
"two:orange": "11"
}
and your desired JSON is:
[
["one","5","10"],
["two","6","11"]
]
Then you can iterate over the keys of your object and add the values of the elements to another hash with shorter keys, and then convert that new hash to an array of arrays.
Example
let json1 = `{
"one:apple": "5",
"one:orange": "10",
"two:apple": "6",
"two:orange": "11"
}`;
function convert(j) {
let o = JSON.parse(j);
let h = {};
for (let k of Object.keys(o)) {
let n = k.split(':')[0];
if (!h[n]) h[n] = [];
h[n].push(o[k]);
}
let a = Object.keys(h).map(k => [k].concat(h[k]));
return JSON.stringify(a);
}
let json2 = convert(json1);
console.log('json1:', json1);
console.log('json2:', json2);
See: DEMO
Example for Node 0.10
This should work on Node v0.10.x:
var json1 = '{\n' +
' "one:apple": "5",\n' +
' "one:orange": "10",\n' +
' "two:apple": "6",\n' +
' "two:orange": "11"\n' +
'}';
function convert(j) {
var o = JSON.parse(j);
var h = {};
for (var k in o) {
if (o.hasOwnProperty(k)) {
var n = k.split(':')[0];
if (!h[n]) h[n] = [];
h[n].push(o[k]);
}
}
var a = Object.keys(h).map(function (k) {
return [k].concat(h[k]);
});
return JSON.stringify(a);
}
var json2 = convert(json1);
console.log('json1:', json1);
console.log('json2:', json2);
See: DEMO
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);
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!