How do i iterate through this JSON object using javascript [duplicate] - javascript

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
How do I pull out ColumnValues[i] using javascript from this JSON sample using two instances with keys = "1" and "2" as shown below. This is just a sample my original JSON object has 500+ entries like this with key = "1", "2", "3", "4", etc. When I retrieve the length of the object the value that is returned equals 1 so using for loop does not work with the length property. Appreciate any help.
JSON object below
[
{
"1": {
"ChildCount": 0,
"ColumnIndentLevel": 0,
"DescendantCount": 0,
"IndentLevel": 0,
"IsCategory": false,
"IsConflict": false,
"IsDocument": true,
"IsTotal": false,
"IsValid": true,
"NoteID": "3962",
"SiblingCount": 2,
"UniversalID": "E8D5D7E88B08CBD686257CD6007470E5",
"ColumnValues": {
"0": "03297",
"1": "Amelia Tang",
"2": "NBK3456",
"3": "FHA",
"4": "2008/10/03 00:00:00 UTC-0000",
"5": "Withdrawn by SASE Administration",
"6": "Approver Level 2",
"7": "Reinstatement"
}
},
"2": {
"ChildCount": 0,
"ColumnIndentLevel": 0,
"DescendantCount": 0,
"IndentLevel": 0,
"IsCategory": false,
"IsConflict": false,
"IsDocument": true,
"IsTotal": false,
"IsValid": true,
"NoteID": "7972",
"SiblingCount": 2,
"UniversalID": "4CEE012B8D60A86A86257CD6007657B0",
"ColumnValues": {
"0": "20004484",
"1": "Anthony Susino",
"2": "",
"3": "Conventional",
"4": "2009/05/11 00:00:00 UTC-0000",
"5": "Withdrawn by SASE Administration",
"6": "",
"7": ""
}
}
}]

Use this:
for (var key in yourObject) { // key will be "1", "2", ...
var value = yourObject[key];
// do something
}

var ColumnValues = /* that object */,
i = 0; //this makes sure the object is iterated in an ascending order
while(i++ in ColumnValuesd){ //and ignores irrelevant properties that are
var item = ColumnValues[i]; //inherited from Object's prototype.
//do something
}
Same goes for the most-top level keys.

Related

How can I display this object in react

I have response from the sarver like this :
{
"response_code": 200,
"tickets": {
"3": {
"117": "http://....../upload/iblock/4a5/4a529553152b21109e9aa18fa9d4ea9b.pdf"
},
"4": {
"118": "http://...../upload/iblock/4a5/4a529553152b21109e9aa18fa9d4ea9b.pdf"
},
"5": {
"119": "http://...../upload/iblock/4a5/4a529553152b21109e9aa18fa9d4ea9b.pdf"
},
"6": {
"120": "http://.../upload/iblock/4a5/4a529553152b21109e9aa18fa9d4ea9b.pdf"
},
"7": {
"121": ""
},
"8": {
"122": "http://..../upload/iblock/4a5/4a529553152b21109e9aa18fa9d4ea9b.pdf"
},
}
}
}
and I should display these links in the websites as it should be an array, but it's an array
so any clue how can I display these links in react app, or how can I convert it to array, so I can display it easily?
If you just want to convert the tickets object to an array of URLs (ignoring any of those number keys), you can do so using Object.values() and Array.prototype.flatMap()
const obj = {"response_code":200,"tickets":{"3":{"117":"http://....../upload/iblock/4a5/4a529553152b21109e9aa18fa9d4ea9b.pdf"},"4":{"118":"http://...../upload/iblock/4a5/4a529553152b21109e9aa18fa9d4ea9b.pdf"},"5":{"119":"http://...../upload/iblock/4a5/4a529553152b21109e9aa18fa9d4ea9b.pdf"},"6":{"120":"http://.../upload/iblock/4a5/4a529553152b21109e9aa18fa9d4ea9b.pdf"},"7":{"121":""},"8":{"122":"http://..../upload/iblock/4a5/4a529553152b21109e9aa18fa9d4ea9b.pdf"}}}
const tickets = Object.values(obj.tickets).flatMap(Object.values)
console.log(tickets)

Filter an array of objects so that no 2 objects are the same [duplicate]

This question already has answers here:
What is the recommended way to filter Objects with Unique property in the array in JS?
(4 answers)
Closed 3 years ago.
I have the following array. If the st and the ct are the same then the objects are considered to be the same. for example the 1st and the 3rd object have the same st and ct so the 3rd should be ignored(filtered out) of the final array. How do I filter this array so that no 2 objects are identical, preferably using the array.filter method? i have read the documentation I just dont get how to express what i want as the conditional for the filter function.
[{
"st": "2012",
"id": "43",
"ct": "1",
"sd": "2"
},
{
"st": "2015",
"id": "45",
"ct": "2",
"sd": "2"
},
{
"st":"2015",
"id": "45",
"ct": "2",
"sd": "1"
},]
You can do:
let uniqueArray = array.filter((o, i, self) => {
return self.findIndex(z => z.ct === o.ct && z.st === o.st) !== i;
});
var objects = [{
"st":"2012",
"id": "43",
"ct": "1",
"sd": "2"
},
{
"st":"2015",
"id": "453",
"ct": "2",
"sd": "2"
},
{
"st":"2012", // this is a duplicate
"ct":"1"
}
];
// Using a Set to keep track of uniqueness avoids iterating through the
// entire array with methods like .findIndex()
var knownKeys = new Set();
var key;
var uniqueObjects = objects.filter(function(obj) {
key = obj.st + obj.ct;
return !knownKeys.has(key) && knownKeys.add(key);
});

JSON/Javascript object definition

Trying to identify the type of array, I have an multidimensional JSON array that i pull from a website, but its not using keypairs i am farmiliar with. The structure is as follows. I have only included 1 array item to show what it's doing.
"o": {
"ah": ["id1", "12", "id2", "32", "id4", "4", "id5, "6"]
},
My searches on both JavaScript and JSON objects and strings always use a semi-colon : to define the key and the value.
In the end I just want to loop through the multiple items and print them out.
To provide more clarification about the array structure:
{
"outer": {
"item1":[ {
"c": {
"k": 26862, "n": "theName"
},
"o": {
"ah": ["id1", "0", "id2", "0", "id3", "0.98", "id4", "0.94", "id5", "5", "id6", "-0/0.5"],
"ou": ["id7", "3.5", "id8", "3.5", "id9", "1.53", "id10", "0.55", "id11", "3.4", "id12"],
"1x2": ["id13", "1.20", "id14", "25.00", "id15", "4.80"]
},
"egn":""
}
]
},
{
"item1":[ {
"c": {
"k": 26862, "n": "theName"
},
"o": {
"ah": ["bd1", "0", "bd2", "0", "bd3", "0.98", "bd4", "0.94", "bd5", "0.5", "bd6", "-0.5"],
"ou": ["bd7", "3.5", "bd8", "3.5", "bd9", "1.53", "bd10", "0.55", "bd11", "3.4", "bd12"],
"1x2": ["bd13", "1.20", "bd14", "25.00", "bd15", "4.80"]
},
"egn":""
}
]
}
}
If I wanted to bind an ID to a specific field e.g. and it display the value of ID 1 in the array structure how would I do it without a keypair value, also if the array ID is not standardized so you can't loop through like var = "id"+ i foreach element?
o is an object, ah is an array which is a property of o object. You use JSON.parse() to convert JSON string to javascript object, then iterate over o.ah using Array.prototype.forEach()
// or however you obtain the JSON string
var obj = JSON.parse(jsonStr);
obj.o.ah.forEach(function(value) {
console.log(value);
});

how to get keys from object list in json string in javascript

[null, {
"display_with": "7",
"id": "1",
"image": "/images/salt_sugar.png",
"name": "Salt and Sugar",
"subcategories": {
"1": true,
"6": true,
"7": true
}
}, {
"display_with": "6",
"id": "2",
"image": "/images/tea_and_coffee.png",
"name": "Tea and Coffee",
"subcategories": {
"8": true,
"9": true,
"124": true
}
}]
In the above string i want 1, 6, 7 and 8, 9, 124 from second and third record respectively.
This is my logic.
recvCategories = JSON STRING
for (var j=0; j<recvCategories.length; ++j){
var category = recvCategories[j];
if (category != undefined){
var subcategories = [];
int size = Object.keys(category.subcategories).length;
for (var property in object) {
if (object.hasOwnProperty(property)) {
// do stuff
}
}
}
}
How to print 1, 6, 7 and 8, 9, 124 in // do stuff ??
Assuming your data is named data this should do it.
var keys = [];
data.forEach(d => {
if (d.subcategories)
for (var key in d.subcategories)
keys.push(key);
})
It may look simple however by using a for(var x in y) will actually iterate the properties of an object and return the propertyNames.
So in the example we call the .forEach() method in an array and then iterate each key of subcategories pushing them into a new array.
Something like,
for( i in aList) {
console.log(keys(aList[i] && aList[i].subcategories))
}
// []
// [1, 6, 7]
// [8, 9, 124]
Few pointers in your code:
This condition: if (category != undefined) will not validate null and code will throw on object.something
Object.keys(category.subcategories).length; will break if you do not have property subcategories in object. You can try something like this (Object.keys(category.subcategories) || []).length
Also if you create your own custom object, then it makes sense to use object.hasOwnProperty, but if you are reading form JSON, you can rely on Object.keys
You can also try something like this:
function getSubCategoriesKeys(d){
return d.reduce(function(p,c){
if(!isEmpty(c) && typeof(c) === "object" && c.hasOwnProperty("subcategories")){
p = p.concat(Object.keys(c.subcategories))
}
return p;
}, [])
}
function isEmpty(o){
return o === undefined || o === null || o.toString().trim().length === 0
}
var data = [null, {
"display_with": "7",
"id": "1",
"image": "/images/salt_sugar.png",
"name": "Salt and Sugar",
"subcategories": {
"1": true,
"6": true,
"7": true
}
}, {
"display_with": "6",
"id": "2",
"image": "/images/tea_and_coffee.png",
"name": "Tea and Coffee",
"subcategories": {
"8": true,
"9": true,
"124": true
}
}]
var keys = getSubCategoriesKeys(data);
console.log(keys)
Reference
what is property in hasownproperty

Javascript Sort key value pair object based on value

I have an object like below. Trying to rearrange it in ascending order based on value. Similar to Javascript array sort method.
var masterList = {
"1": "google",
"2": "yahoo",
"3": "msn",
"4": "stackoverflow",
"5": "github",
"6": "jsfiddle",
"7": "amazon",
"8": "ebay"
}
Please let me know the better solution...
JavaScript objects have no order. Even though most browsers do iterate in the same order the properties were created, there's no guarantee, so sorting is not supported on objects.
See here for more info: Does JavaScript Guarantee Object Property Order?
You might also be interested in what John Resig has got to say on the matter.
If you need a sort-able list, you'll have to store it as an array of objects:
var masterList = [
{ key: 1, val: "google" },
{ key: 2, val: "yahoo" },
{ key: 3, val: "msn" },
{ key: 4, val: "stackoverflow" },
{ key: 5, val: "github" },
{ key: 6, val: "jsfiddle" },
{ key: 7, val: "amazon" },
{ key: 8, val: "ebay" }
];
Then, to sort them, just use the regular array's sort method:
masterList = masterList.sort(function (a, b) {
return a.val.localeCompare( b.val );
});
Here's the fiddle: http://jsfiddle.net/ASrUD/
var obj = {
"1": "google",
"2": "yahoo",
"3": "msn",
"4": "stackoverflow",
"5": "github",
"6": "jsfiddle",
"7": "amazon",
"8": "ebay"
};
var arr = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
arr.push(obj[key]);
}
}
alert(arr.sort());
This will sort your values in ascending order. let me give sometime will revert you with how to convert that to an object.
var masterList = {
"2": "yahoo",
"3": "msn",
"4": "stackoverflow",
"5": "github",
"6": "jsfiddle",
"7": "amazon",
"8": "ebay",
"1": "google",
}
var masterList_ = {}
Object.keys(masterList).sort().forEach(a=>masterList_[a]=masterList[a])
console.log(masterList_)

Categories