This question already has answers here:
Sort JavaScript object by key
(37 answers)
Sorting object property by values
(44 answers)
Closed 9 years ago.
I have an object that looks like:
{
"2013": {
"name": 2013,
"ts_create": 1375254000000,
"view_url": "some_url",
"save_url": "some_url_2",
"id": "",
"exists": true,
"children": []
},
"2012": {
"name": 2013,
"ts_create": 1375254000000,
"view_url": "some_url",
"save_url": "some_url_2",
"id": "",
"exists": true,
"children": []
},
"2011": {
"name": 2013,
"ts_create": 1375254000000,
"view_url": "some_url",
"save_url": "some_url_2",
"id": "",
"exists": true,
"children": []
}
}
The problem I am facing is, it seems only in Google Chrome that when I loop over this object the objects loop backwards.
The expected result of looping over and displaying the object should list out things from 2013, 2012, 2011. Which happens in Firefox.. However no change in the method, same exact object in Chrome.. I will get 2011, 2012, 2013
So with this I need to obviously apply some level of sorting over this object before looping over it, seeing as Chrome wants to get the loop to read over it backwards. Problem I am facing with that is not entirely sure how to sort an object with JS
Instead of property/value pair implement this structure as an array of objects. Arrays you can sort by any property of objects it contains.
Because objects are unordered collections, it's up to you to enforce the ordering you want.
One way is to get an Array of the object properties, sort them, then iterate the Array.
Object.keys(data)
.sort(function(a, b) {
return +b - +a;
})
.forEach(function(key) {
var item = data[key];
});
This assumes that you wanted a simple descending order.
When you iterate over object properties, there is no guarantee on the order. You can add your objects to an array, and sort the array instead:
var obj = {"2012" : {}, "2011" : {}, "2013" : {}};
var arr = [];
for (var year in obj) {
arr.push({year : year, data : obj[year]});
}
arr.sort(function(a,b) {
return b.year - a.year;
});
http://jsfiddle.net/wK5KE/
One way to get the keys in sorted order would be to use the method defined here to generate an array of the keys:
Getting JavaScript object key list
Then you could use the javascript sort function:
http://www.w3schools.com/jsref/jsref_sort.asp
Or write your own if you feel inclined.
Then just loop through the array of keys, using object[key] to extract the value.
Related
Given this data structure:
{ "name": [ "can't be blank" ], "league_id": [ "You already have a team in this league." ] }
How can I print this?
Can't be blank
You already have a team in this league
So basically I want to iterate through the values of the object. How can I do this with Javascript? Thank You!
Your data structure doesn't make much practical sense in that your property values are arrays with just one element in them. While legal, for the data you are showing, it makes more sense just to have the strings as the values.
Either way, a for/in loop over the object will allow you to iterate the keys.
With current structure:
let obj = {
"name": ["can't be blank"],
"league_id": ["You already have a team in this league."]
};
for(var key in obj){
console.log(obj[key][0]); // Here, you have to index the property value, which is an array
}
With arrays removed:
let obj = {
"name": "can't be blank",
"league_id": "You already have a team in this league."
};
for(var key in obj){
console.log(obj[key]); // Here, you can access the key value directly
}
You can also use Object.keys(obj), along with a .forEach() method call, which is a newer technique:
let obj = {
"name": ["can't be blank"],
"league_id": ["You already have a team in this league."]
};
Object.keys(obj).forEach(function(key){
console.log(obj[key][0]); // Here, you have to index the property value, which is an array
});
Let's see:
const obj = { "name": [ "can't be blank" ], "league_id": [ "You already have a team in this league." ] }
console.log(Object.values(obj).map(value => value.toString()).join("\n"))
Get values of the keys in object with Object.values method
map over them
Since the value itself is Array, cast it to string (or get the first element)
Join them with a new line
This question already has answers here:
Get array of object's keys
(8 answers)
Closed 4 years ago.
I am currently trying to handle a GET request that returns a body in application/json structured like this:
{
"items": {
"item001": {"id":1234, "name": "name001"},
"item002": {"id":1235, "name": "name002"},
"item003": {"id":1236, "name": "name003"}
}
}
I'm trying to get an array of strings that looks like
array = ["item001", "item002", "item003"];
I don't care about any of the underlying hierarchy, I just need the key of each object as an array. I've tried several different methods (map(), JSON.stringify(), etc) but I can't seem to index each key in a array[i] format.
In fact, each time I try to even print the name of a single key, for example
var obj = JSON.parse({'whole json here'});
print(obj.items[1]);
I get an [object Object] error, which makes sense as obj.items is not indexed with a key other than "item001" for example. However, I do not know what the key for each object will be, hence the need for an array of the keys. Thank you in advance!
You can do Object.keys.It will return an array of the keys of an object
var x = {
"items": {
"item001": {
"id": 1234,
"name": "name001"
},
"item002": {
"id": 1235,
"name": "name002"
},
"item003": {
"id": 1236,
"name": "name003"
}
}
}
var y = Object.keys(x.items);
console.log(y)
You can use Object.keys(). For Reference
var obj={"items":{"item001":{"id":1234,"name":"name001"},"item002":{"id":1235,"name":"name002"},"item003":{"id":1236,"name":"name003"}}};
var result = Object.keys(obj.items);
console.log(result);
Object.keys will do that.
var obj = JSON.parse({'your json'});
console.log( Object.keys(obj.items) );
This question already has answers here:
How to iterate over a JavaScript object?
(19 answers)
Closed 6 years ago.
I'm trying to convert a JSON key value object to an Array, but I'm not sure how to get it in the format I need. What I have for the JSON is something similar to below:
{
"01": "yes",
"02": "yes",
"03": "no"
}
but I need an Array like the one below so I can iterate through it easily:
["01:yes","02:yes","03:no"]
or is it possible to iterate through this JSON object while accessing the keys and values easily?
Use Array#reduce
Object.keys() returns an array of a given object's own enumerable properties
var obj = {
"01": "yes",
"02": "yes",
"03": "no"
};
var op = Object.keys(obj).reduce(function(a, b) {
return a.concat(b + ':' + obj[b]);
}, []);
console.log(op);
This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 8 years ago.
Problem: Create a javascript function that takes an object (of any size and depth), iterates through it and runs some basic string replacing on any strings and returns the object with the amended values.
I have two ideas about the implementaion, but cannot get a solution for either:
var context = {
"test1": "123",
"test2": "123",
"test2.2": "123",
"test3": {
"test4": "cats",
"test5": {
"test6": "test1",
"test123": "1231232"
}
}
};
Idea 1)
Loop the array, and change the values,
http://php.net/manual/en/language.references.pass.php
In some way similar to PHP
Idea 2)
Build an array of path(s) to the object, so to replace the "test123" value I can create such an array:
['test3', 'test5', 'test123']
... this part is simple, but how do I then convert this to something like:
context['test3']['test5']['test123'] ?
Thankyou in advance.
Loop over the object and invoke the function recursively if the value at hand is an object. In pseudocode:
function replaceInObject ( obj, find, repl)
for key in obj
value = obj[key]
if value is object
obj[key] = replaceInObject(value, find, repl)
else
obj[key] = value.replace(find, repl)
return obj
I have the following array structure:
rgInventory": {
"2085630349": {
"id": "2085630349",
"classid": "253266389",
"instanceid": "253354499",
"amount": "1",
"pos": 1
},
"1938126110": {
"id": "1938126110",
"classid": "57939745",
"instanceid": "0",
"amount": "1",
"pos": 2
},
...
I need to be able to identify which child of rgInventory has the property pos = 1, and then return the id of this child array (in the example above, this would be 2085630349.
Thanks!
What you have is not an array, just an object.
You can loop through the keys of an object using a for-in loop, like this:
var key;
for (key in obj) {
// `key` will be each key, in no particular order
}
It loops not only through the object's own properties, but through enumerable properties it inherits from its prototype. Simple objects like the one you have there don't inherit any enumerable properties from their prototype (unless someone does something really silly, below), but if you wanted to be sure, you could use if (obj.hasOwnProperty(key)) in the loop above to only handle its own and not inherited ones.
Then just look at obj[key], which is a reference to the child object, and see if it has the relevant pos property.
Just for completeness, the really silly thing would be this:
Object.prototype.someName = /* some value */;
...which would create an enumerable property on the prototype used for simple objects. This should never be done.