I want to iterate through nested Object and I want to store the all the child keys path as separate array
{
"A": {
"C": {
"G": {}
}
},
"B": {
"D": {
"G": {}
},
"E": {
"H": {}
},
"F": {
"I": {
"H": {}
},
"J": {}
}
}
}
I need Array in below format.
A,C,G
B,D,G
B,E,H
B,F,J
B,F,I,H
You can use recursion with Object.entries to get the values.
Here is an example.
const data = {
"A": {
"C": {
"G": {}
}
},
"B": {
"D": {
"G": {}
},
"E": {
"H": {}
},
"F": {
"I": {
"H": {}
},
"J": {}
}
}
};
const result = []
function getPaths(data,path=''){
const list = Object.entries(data)
if(!list.length){
result.push(path)
return
}
list.forEach(([key,value])=>getPaths(value,path ? path+','+key : key))
}
getPaths(data)
console.log(result)
Related
I have to iterate through this JSON:
{
"data": 321563,
"group": [
{
"added": 42421,
"normal": {
"x": 39,
"y": "0.1300",
"b": "0.4326",
"c": "0.0552",
"f": 166833
},
"j": "240313",
"b": "0.2251",
"a": "dda",
"b": "0.101",
"a": 922,
"f": {
"c": 39,
"d": "0.263",
"a": "2.8955",
"h": "0.3211",
"d": 274
},
"a": false,
"k": 5,
"w": "0.072",
"d": "0.045",
"e": 3
},
I only want the j and k stored like a key value pair e.g. "j":k
I need to loop all of it, and store it to a file.
You can use a map to get a new array of items, this will not affect the old array.
const data = {
"game_count": 8750,
"sets": [
{
"appid": "221540",
"true_count": 9,
"bgs_avg": "0.10",
// Other data here
},
{
"appid": "123456",
"true_count": 9,
"bgs_avg": "0.20",
// Other data here
}
]
}
// Use "data.sets = data.sets.map(...)" to replace the data
// The following will only assign to a new variable
const newArray = data.sets.map(itm => { return {appid: itm.appid, true_count: itm.true_count} })
console.log(newArray)
We can also take the data and assign it directly back to the original overwriting it just by using data.sets = data.sets.map(...) as seen here:
const data = {
"game_count": 8750,
"sets": [
{
"appid": "221540",
"true_count": 9,
"bgs_avg": "0.10",
// Other data here
},
{
"appid": "123456",
"true_count": 9,
"bgs_avg": "0.20",
// Other data here
}
]
}
data.sets = data.sets.map(itm => { return {appid: itm.appid, true_count: itm.true_count} })
console.log(data)
In simple javascript this should work -
let newObj = {}
for(let i=0; i<obj.group.length; i++){
newObj[obj.group[i].j] = obj.group[i].k
}
Where 'obj' is your object
newObj will be you new Object which will contain all the key value pair
I want to change the below JSON Data to Expected Format.
JSON DATA:
[
{
"A": {
"X": "P"
},
"B": {
"X": "Q"
},
"C": {
"X": "R"
}
}
]
Expected Format:
[
{
"A": "P",
"B": "Q",
"C": "R"
}
]
Thanks in advance. :)
Try this. You can get the keys of the each item and then map to the correspond structure of object.
const json = [
{
"A":{
"X":"P"
},
"B":{
"X":"Q"
},
"C":{
"X":"R"
}
}
];
const expectedJSON = json.map(item => {
const obj = {};
Object.keys(item).forEach(key => obj[key] = item[key].X);
return obj;
})
console.log(expectedJSON);
In case X property has different names for each object you can use this method.
const json = {
"A": { "X": "P" },
"B": { "X": "Q" },
"C": { "X": "R" }
};
for (let prop in json) {
for (let item in json[prop]) {
json[prop] = json[prop][item];
}
}
console.log(json);
I am wanting to write a function to turn a JSON object's keys into more appropriate names. As you can see by the JSON object below, the keys are 1 letter and are not very readable or useful for anyone. Therefore I would like to loop through the object (or something similar) and rename all the keys, and then return this JSON.
{
"e": "56049",
"pp": "371861",
"c": "GAME",
"x": 2,
"st": "2017-04-27T15:01:29Z",
"o": 0,
"r": true,
"u": "2017-04-27T15:01:29Z",
"t": "p",
"i": "371871",
"z": 1493305289586
}
You can reduce object keys to new object, e.g.:
const obj = {
"e": "56049",
"pp": "371861",
"c": "GAME",
"x": 2,
"st": "2017-04-27T15:01:29Z",
"o": 0,
"r": true,
"u": "2017-04-27T15:01:29Z",
"t": "p",
"i": "371871",
"z": 1493305289586
}
// [key] -> [normalized name] mapping
const names = {
"e": "e-name",
"pp": "pp-name",
"c": "c-name",
"x": "x-name",
"st": "st-name",
"o": "o-name",
"r": "r-name",
"u": "u-name",
"t": "t-name",
"i": "i-name",
"z": "z-name"
}
const renamedProps = Object.keys(obj).reduce((renamed, key) => {
renamed[names[key]] = obj[key];
return renamed;
}, {});
var obj = {
"e": "56049",
"pp": "371861",
"c": "GAME",
"x": 2
},
names = ["e_new-name", "pp_new-name", "c_new-name", "x_new-name"],
updated = {},
keys = Object.keys(obj);
for (i = 0; i < keys.length; i++) {
updated[names[i]] = obj[keys[i]];
}
console.log(JSON.stringify(updated));
// will print
// {"e_new-name":"56049","pp_new-name":"371861","c_new-name":"GAME","x_new-name":2}
jsfiddle
i am struggling how to sum all the values of "B" in my json object. I want the console log to show me the grand total of all the "B" values.
var voltot = 0;
$.each(json,function(k,v){
voltot = v.B += voltot ;
//console.log(v.B);
});
console.log(voltot);
HERE IS MY FULL JSON OBJECT.
var json=
[
{
"a": "OOCBER",
"b": "OOCL BERLIN",
"c": "CHINA",
"d": "GREAT BRITAIN",
"e": "*PI",
"f": "NGB",
"g": "CN",
"i": "GB",
"n": 9,
"o": 6,
"p": "2015-09-14",
"q": "2015-09-14",
"s": 4,
"u": "40HC",
"v": "TRLU7564566",
"w": "CN0794909",
"x": "LEIGH",
"y": "NINGBO",
"z": 395,
"B": 68.8,
"C": 7987.5,
},
{
"a": "OOCBER",
"b": "OOCL BERLIN",
"c": "CHINA",
"d": "GREAT BRITAIN",
"e": "*PI",
"f": "NGB",
"g": "CN",
"i": "GB",
"n": 9,
"o": 6,
"p": "2015-09-14",
"q": "2015-09-14",
"s": 4,
"u": "40HC",
"v": "TCLU8306124",
"w": "CN0786008",
"x": "OXFORDSHIRE",
"y": "NINGBO",
"z": 412,
"B": 68,
"C": 8790.5,
}
]
i am struggling how to sum all the values of "B" in my json object. I want the console log to show me the grand total of all the "B" values.
var voltot = 0;
$.each(json,function(k,v){
voltot = v.B += voltot ;
//console.log(v.B);
});
console.log(voltot);
This is wrong
voltot = v.B += voltot ;
Make like this
voltot += v.B;
Or
voltot = v.B + voltot ;
The preferred method to obtain an unique value from an array is the Array.prototype.reduce method, which takes a callback function and a starting value (it reduces an array to a single value). You could use it this way :
json.reduce(function(total, current) { return typeof current.B === "number" ? total + current.B : total; }, 0);
Here is a JSFiddle.
Here's JSFiddle. I just shrunk json and post. Try with full json array
var json=
[
{
"z": 395,
"B": 68,
"C": 7987.5,
},
{
"z": 395,
"B": 68,
"C": 7987.5,
}
];
var voltot = 0;
$.each(json,function(k,v){
voltot += v.B;
});
console.log(voltot);
The operator += is incorrect. #RiccardoC answer was correct.
Also, you don't need to use jquery to sum the values. You could simply do the following
var voltot=0;
json.forEach(function(element) {voltot+=element.B})
The forEach function will run a callback for each element of your array
I want to update one combobox by changing the second combobox.
for example:
I have this response (string):
var response = [{
"A": "a2",
"B": "b2",
"C": "c2"
},
{
"A": "a3",
"B": "b3",
"C": "c3"
},
{
"A": "a3",
"B": "b331",
"C": "c33"
},
{
"A": "a3",
"B": "b33221",
"C": "c3"
},
{
"A": "a4",
"B": "b4",
"C": "c4"
},
{
"A": "a2",
"B": "b221",
"C": "c222"
}];
and I want that in "myDropDownA" will be "a2, a3, a4".
and for example:
if I choose "a3" in "myDropDownA", than in "myDropDownB" will appear only: "b3, b331, b33221" (because they only refer to a3).
and I don't want repeated of "A" objects.
var myDropDownA = $("#myDropDownA");
$.each(response, function (index, obj) {
//alert(index + ": " + obj.A);
myDropDownA.append($("<option />").val(obj.A).text(obj.A));
});
var myDropDownB = $("#myDropDownB");
$.each(response, function (index, obj) {
//alert(index + ": " + obj.B);
myDropDownB.append($("<option />").val(obj.B).text(obj.B));
});
what do I need to change (or to add) to make it work as above?
What you're missing is attaching an eventhandler to the change event of dropdown A repopulating dropdown B with relevant values.
var response = [
{ "A": "a2", "B": "b2", "C": "c2" },
{ "A": "a3", "B": "b3", "C": "c3" },
{ "A": "a3", "B": "b331", "C": "c33" },
{ "A": "a3", "B": "b33221", "C": "c3" },
{ "A": "a4", "B": "b4", "C": "c4" },
{ "A": "a2", "B": "b221", "C": "c222"}
];
var uniqueByProperty = function(arr, prop) {
var seen = {};
return arr.filter(function(elem) {
var val = elem[prop];
return (seen[val] === 1) ? 0 : seen[val] = 1;
})
}
var aList = uniqueByProperty(response, "A");
var myDropDownA = $("#myDropDownA");
var myDropDownB = $("#myDropDownB");
// Populate dropdown A
$.each(aList, function(index, obj) {
myDropDownA.append($("<option />").val(obj.A).text(obj.A));
});
// Attach event handler for dropdown A
myDropDownA.on('change', function(){
var ddl = $(this);
// Get related objects
var bList = response.filter(function(elem) {
return (elem.A === ddl.val());
});
// Populate dropdown B
myDropDownB.empty();
$.each(bList, function(index, obj) {
myDropDownB.append($("<option />").val(obj.B).text(obj.B));
});
});
// Trigger population of dropdown B
myDropDownA.change();
See this jsfiddle for a working demonstration.