Javascript loop through object of many objects - javascript

I have a string JSON http response.
{
"1537988400000": {
"6495": ["18", "29"],
"6490": ["34", "40"],
"6500": ["7", "213"],
"6505": ["13", "17"]
},
"1537992000000": {
"6490": ["45", "87"],
"6485": ["15", "4"],
"6495": ["78", "222"],
"6500": ["176", "141"],
"6505": ["64", "94"],
"6510": ["7", "53"],
"6515": ["0", "1"]
}
}
I want to parse it to a JavaScript object. The object must be structured so that I could get the numbers from the arrays. For instance, I choose "1537992000000" -> "6495" -> [1] and get '222'.
Here is my code:
var resp = this.responseText; // JSON string
var object = JSON.parse(resp);
for (var obj in object) {
for (var a in obj) {
alert(a[0]); // should return the first number in the array of an object
}
}
The problem is that it doesn't return numbers. It sends something like 0,1..9,10.. (Seems like these are the indexes of each property's properties)

Your JSON pase logic is fine, you have mistaken here, obj is key
for (var obj in object)
The object must be structured so that I could get the numbers from the arrays.
var json={"1537988400000":{"6495":["18","29"],"6490":["34","40"],"6500":["7","213"],"6505":["13","17"]},"1537992000000":{"6490":["45","87"],"6485":["15","4"],"6495":["78","222"],"6500":["176","141"],"6505":["64","94"],"6510":["7","53"],"6515":["0","1"]}}
for(var i in json){
for(var j in json[i]){
console.log(json[i][j]);
}
}

for(var a in obj){
Seems like these are the indexes of each property's properties
Yes. That is what in does. Use of to loop over values.

var data = '{"1537988400000":{"6495":["18","29"],"6490":["34","40"],"6500":["7","213"],"6505":["13","17"]},"1537992000000":{"6490":["45","87"],"6485":["15","4"],"6495":["78","222"],"6500":["176","141"],"6505":["64","94"],"6510":["7","53"],"6515":["0","1"]}}';
data = JSON.parse(data);
for (var obj in data) {
for (var a in data[obj]) {
console.log(data[obj][a]);
}
}

Related

JS: Finding next key in json

I have the following json:
{0: "2", 1: "2", $$hashKey: "object:35", undefined: "1"}
Currently I am trying to get its key-value with the below code:
var data = JSON.stringify(row);
var result = $.parseJSON(data);
$.each(result, function (k, v) {
//display the key and value pair
console.log(k, v);
});
The above code works fine and I can get my key-value from it.
Now what I am trying to get is the next key-value pairs within the $.each loop.
For example if in the loop the current key is "0" I want to get the next key "1" in the same call itself. If in the loop the current key is "1" I want to get the next key "$$hashKey" along with their values.
Is it possible to do so? I am open to code changes above if required.
You can use Object.keys to get the keys to an array, then run through it with a forEach to have access to the keys index. Important to note that objects are unordered, so your key order one time may differ from the next time:
var keys = Object.keys(obj);
keys.forEach(function(key, index) {
var nextIndex = index + 1;
if (nextIndex === keys.length) return; //out of bounds
var nextKey = keys[nextIndex];
});
Edit: As pointed out by the comments - if you want the keys in the same order each time, call .sort() on your keys array with your desired sort logic.
Understanding now that the goal is to retrieve keys in the order they appear in JSON, a couple of thoughts:
(1) if you control the source of the object ("row" in the OP code), don't represent it as an object. instead use an array of key-value pairs: [[0, "2"], [1, "2"], [$$hashKey, "object:35"], [undefined, "1"]].
otherwise, (2) roll your own JSON parser that returns an array of key-value pairs for an object. This post looks to be a sensible start. Or, you can vastly simplify the task if you are able to make certain assumptions about the values, for example, say you know that all values are strings...
// parse a string representing an object, returning an array of key-value pairs.
// assumes values are strings that do not contain commas or colons
function myProbablyNegligentlySimpleJSONParse(string) {
let trimmed = string.trim().slice(1, -1);
let components = trimmed.split(',');
return components.map(kvString => {
let kv = kvString.split(':');
return [ kv[0].trim(), kv[1].trim() ];
});
}
forEach passes the current index to the iterator function, so that int can be used to look ahead or behind in the iteration.
var data = '{0: "2", 1: "2", $$hashKey: "object:35", undefined: "1"}';
let result = myProbablyNegligentlySimpleJSONParse(data);
result.forEach(function (pair, index) {
let [k, v] = pair; // now k and v are your key and value
console.log(`key is ${k} value is ${v}`)
if (index < result.length-1) {
let [nextK, nextV] = result[index+1];
console.log(`next key is ${nextK} next value is ${nextV}`);
}
});
You could turn your object into an iterable and which will return the next [key, value] pair each time you call next on the iterator:
function makeIterable(o) {
o[Symbol.iterator] = () => {
var keys = Object.keys(o);
var i = 0;
return {
next() {
var done = false;
var value = [keys[i + 1], o[keys[i + 1]]];
if (i >= (keys.length - 1)) {
done = true;
}
i++;
return {
value,
done
}
}
};
}
}
var jsonStr = '{ "0": "2", "1": "2", "$$hashKey": "object:35", "undefined": "1" }';
var obj = JSON.parse(jsonStr);
makeIterable(obj);
var itr = obj[Symbol.iterator]();
while (true) {
var item = itr.next();
if (item.done) {
break;
}
console.log(item.value);
}

JS: Convert a specific values from an object into an array?

I have an object:
var obj =
[
{
"value": "aep",
"label": "AEP"
},
{
"value": "cap",
"label": "CAP"
},
{
"value": "casl",
"label": "CASL"
} ]
And I want to convert the values of the labels ONLY into an array so that the end result is:
["AEP", "CAP", "CASL"]
How do I only get the label values converted in an array?
First: obj is not an object, it is an array since the parent brackets are [] and not {}. I will, however, keep the name the same. This might have caused you some confusion, e.g.
var object = {};
var array = [];
var arrayOfObjects = [{},{},{}];
var objectOfArrays = {array1: [],array2: [],array3: []};
To loop an array you can use a for loop:
// new array
var newArray = [];
// iterates over each index in the array
for(var i=0; i<obj.length; i++) {
// Access the specific index, then access its `label` property
// Push into `newArray`
newArray.push(obj[i].label);
}
console.log(newArray);
Codepen: http://codepen.io/theblindprophet/pen/RRxVba
Using a for loop
var out = [];
for (var i = 0, len = obj.length; i < len; i++) {
out.push(obj[i].label);
}
console.log(out);
Its simple. You can use map function of javascript array
var obj =
[
{
"value": "aep",
"label": "AEP"
},
{
"value": "cap",
"label": "CAP"
},
{
"value": "casl",
"label": "CASL"
} ]
var arr = obj.map(function(data){return data.value});
This is a functional solution and not the most straightforward one, you may want to refer to #theblindprophet's answer for the imperative approach to this problem.
Pretty easy task to be done in a functional way:
var labels = obj.map(function(inner) { return inner.label });
How does one approach such a problem: You need to think of how to transform the data you have to the data you want. In this case you have an Array of Objects and you want to transform this Array of Objects to an Array of Strings placed inside that Object.
The above code iterates over the Array and returns the value you want for the current element of the Array, building a new Array in the course (map)

Converting JavaScript object with numeric keys into array

I have an object like this coming back as a JSON response from the server:
{
"0": "1",
"1": "2",
"2": "3",
"3": "4"
}
I want to convert it into a JavaScript array like this:
["1","2","3","4"]
Is there a best way to do this? Wherever I am reading, people are using complex logic using loops. So are there alternative methods to doing this?
It's actually very straight forward with jQuery's $.map
var arr = $.map(obj, function(el) { return el });
FIDDLE
and almost as easy without jQuery as well, converting the keys to an array and then mapping back the values with Array.map
var arr = Object.keys(obj).map(function(k) { return obj[k] });
FIDDLE
That's assuming it's already parsed as a javascript object, and isn't actually JSON, which is a string format, in that case a run through JSON.parse would be necessary as well.
In ES2015 there's Object.values to the rescue, which makes this a breeze
var arr = Object.values(obj);
var json = '{"0":"1","1":"2","2":"3","3":"4"}';
var parsed = JSON.parse(json);
var arr = [];
for (var x in parsed) {
arr.push(parsed[x]);
}
console.log(arr)
Hope this is what you're after!
You simply do it like
var data = {
"0": "1",
"1": "2",
"2": "3",
"3": "4"
};
var arr = [];
for (var prop in data) {
arr.push(data[prop]);
}
console.log(arr);
DEMO
There is nothing like a "JSON object" - JSON is a serialization notation.
If you want to transform your javascript object to a javascript array, either you write your own loop [which would not be that complex!], or you rely on underscore.js _.toArray() method:
var obj = {"0":"1","1":"2","2":"3","3":"4"};
var yourArray = _(obj).toArray();
Nothing hard here. Loop over your object elements and assign them to the array
var obj = {"0":"1","1":"2","2":"3","3":"4"};
var arr = [];
for (elem in obj) {
arr.push(obj[elem]);
}
http://jsfiddle.net/Qq2aM/
var JsonObj = {
"0": "1",
"1": "2",
"2": "3",
"3": "4"
};
var array = [];
for (var i in JsonObj) {
if (JsonObj.hasOwnProperty(i) && !isNaN(+i)) {
array[+i] = JsonObj[i];
}
}
console.log(array)
DEMO
Try this:
var newArr = [];
$.each(JSONObject.results.bindings, function(i, obj) {
newArr.push([obj.value]);
});
You can use Object.assign() with an empty array literal [] as the target:
const input = {
"0": "1",
"1": "2",
"2": "3",
"3": "4"
}
const output = Object.assign([], input)
console.log(output)
If you check the polyfill, Object.assign(target, ...sources) just copies all the enumerable own properties from the source objects to a target object. If the target is an array, it will add the numerical keys to the array literal and return that target array object.
var obj = {"0":"1","1":"2","2":"3","3":"4"};
var vals = Object.values(obj);
console.log(vals); //["1", "2", "3", "4"]
Another alternative to the question
var vals = Object.values(JSON.parse(obj)); //where json needs to be parsed
Using raw javascript, suppose you have:
var j = {0: "1", 1: "2", 2: "3", 3: "4"};
You could get the values with:
Object.keys(j).map(function(_) { return j[_]; })
Output:
["1", "2", "3", "4"]
Not sure what I am missing here but simply trying the below code does the work. Am I missing anything here?
https://jsfiddle.net/vatsalpande/w3ew5bhq/
$(document).ready(function(){
var json = {
"code" :"1",
"data" : {
"0" : {"id":"1","score":"44"},
"1" : {"id":"1","score":"44"}
}
};
createUpdatedJson();
function createUpdatedJson(){
var updatedJson = json;
updatedJson.data = [updatedJson.data];
$('#jsondata').html(JSON.stringify(updatedJson));
console.log(JSON.stringify(updatedJson));
}
})
Assuming your have a value like the following
var obj = {"0":"1","1":"2","2":"3","3":"4"};
Then you can turn this into a javascript array using the following
var arr = [];
json = JSON.stringify(eval('(' + obj + ')')); //convert to json string
arr = $.parseJSON(json); //convert to javascript array
This works for converting json into multi-diminsional javascript arrays as well.
None of the other methods on this page seemed to work completely for me when working with php json-encoded strings except the method I am mentioning herein.
Here is an example of how you could get an array of objects and then sort the array.
function osort(obj)
{ // map the object to an array [key, obj[key]]
return Object.keys(obj).map(function(key) { return [key, obj[key]] }).sort(
function (keya, keyb)
{ // sort(from largest to smallest)
return keyb[1] - keya[1];
}
);
}
This is best solution. I think so.
Object.keys(obj).map(function(k){return {key: k, value: obj[k]}})
The accepted solution expects the keys start from 0 and are continuous - it gets the values into the array, but looses the indexes on the way.
Use this if your "object with numerical keys" does not fulfill those stricter assumptions.
//let sourceObject = ...
let destinationArray = [];
Object.keys(sourceObject).forEach(k => destinationArray[k] = sourceObject[k]);
var data = [];
data = {{ jdata|safe }}; //parse through js
var i = 0 ;
for (i=0;i<data.length;i++){
data[i] = data[i].value;
}
You can convert json Object into Array & String using PHP.
$data='{"resultList":[{"id":"1839","displayName":"Analytics","subLine":""},{"id":"1015","displayName":"Automation","subLine":""},{"id":"1084","displayName":"Aviation","subLine":""},{"id":"554","displayName":"Apparel","subLine":""},{"id":"875","displayName":"Aerospace","subLine":""},{"id":"1990","displayName":"Account Reconciliation","subLine":""},{"id":"3657","displayName":"Android","subLine":""},{"id":"1262","displayName":"Apache","subLine":""},{"id":"1440","displayName":"Acting","subLine":""},{"id":"710","displayName":"Aircraft","subLine":""},{"id":"12187","displayName":"AAC","subLine":""}, {"id":"20365","displayName":"AAT","subLine":""}, {"id":"7849","displayName":"AAP","subLine":""}, {"id":"20511","displayName":"AACR2","subLine":""}, {"id":"28585","displayName":"AASHTO","subLine":""}, {"id":"45191","displayName":"AAMS","subLine":""}]}';
$b=json_decode($data);
$i=0;
while($b->{'resultList'}[$i])
{
print_r($b->{'resultList'}[$i]->{'displayName'});
echo "<br />";
$i++;
}

javascript: How to get highest layer of json object as array?

With an array of objects in a form like this:
[
{
1429={
{
8766={...},
8483={...},
7345={...}
}
}
},
{
9041={...}
}
]
how could i get back an array like this?:
[1429, 9041]
If the array of objects would be in another structure this code would work:
var obj = {
"5": "some",
"8": "thing"
};
var keys = $.map(obj, function (value, key) {
return key;
});
console.log(keys);
That would return [5, 8]. But in my example it just would return the indexes [0,1]
Even if I wouldn't know the depth of the object - is it possible to get the values on that level? I dont need the indexes, I need those values. I couldn't find anything about it so far. Any tips for me maybe?
P.S.: I know that i could work out something with these keys and a loop, but I'm just asking for a simplier way to do it.
Regards
you are looking for the keys in a json object, you can get them this way:
Object.keys(obj);
for the object example:
var obj = {
"5": "some",
"8": "thing"
};
you will get:
["5","8"]
for an array of object of this type:
var arrayObject = [{},{},{}];
you can use a map and get the keys:
var keys = arrayObject.map(function(k){
return Object.keys(k);
});
keys is an array of arrays of keys. Example, for the following object (similar to your data structure):
var l= [
{
1429:{
8766: "test",
8483:"test",
7345: "test"
}
},
{
9041: "test"
}
];
you will get:
[["1429"],["9041"]]
apply concat and you will get what you are looking for. Here how to apply concat in the case of multiple arrays.
var arrayOfKeys = [].concat.apply([], keys);
now you will get:
["1429","9041"];
In your specific case you could use
var keys = [];
root.forEach(function(v) { keys = keys.concat(Object.keys(v)); });
If instead you have a tree of arrays and you want the keys of all other objects instead (but not recursing into objects) then a simple recursive function would do it:
function topKeys(x) {
if (x && x.constructor === Array) {
var result = [];
x.forEach(function(item) {
result = result.concat(topKeys(item));
});
return result;
} else if (typeof x === "object") {
return Object.keys(x);
} else {
return [];
}
}

JSON.stringify serializes to [[]]

If I create a JavaScript object like:
var lst = [];
var row = [];
row.Col1 = 'val1';
row.Col2 = 'val2';
lst.push(row);
And then convert it to a string:
JSON.stringify(lst);
The result is an object containing an empty object:
[[]]
I would expect it to serialize like:
[[Col1 : 'val1', Col2: 'val2']]
Why do the inner objects properties not serialize?
Code snippet at JSFiddle.
Because row is an array, not an object. Change it to:
var row = {};
This creates an object literal. Your code will then result in an array of objects (containing a single object):
[{"Col1":"val1","Col2":"val2"}]
Update
To see what really happens, you can look at json2.js on GitHub. This is a (heavily reduced) snippet from the str function (called by JSON.stringify):
if (Object.prototype.toString.apply(value) === '[object Array]') {
//...
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
//...
}
//...
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
//...
}
//...
}
//...
Notice that arrays are iterated over with a normal for loop, which only enumerates the array elements. Objects are iterated with a for...in loop, with a hasOwnProperty test to make sure the proeprty actually belongs to this object.
You use your inner array like an object, so make it an object instead of an array.
var lst = [];
var row = {};
row.Col1 = 'val1';
row.Col2 = 'val2';
lst.push(row);
or use it as an array
var lst = [];
var row = {};
row.push( 'val1' );
row.push( 'val2' );
lst.push(row);
You want row to be a dictionary, not a vector. Define it like this:
var row = {};
Since an array is a datatype in JSON, actual instances of Array are stringified differently than other object types.
If a JavaScript Array instance got stringified with its non-numeric keys intact, it couldn't be represented by the [ ... ] JSON array syntax.
For instance, [ "Col1": "val1"] would be invalid, because JSON arrays can't have explicit keys.
{"Col1": "val1"} would be valid - but it's not an array.
And you certainly can't mix'n'match and get { "Col1": "val1", 1, 2, 3 ] or something.
By the way, this works fine:
var lst = [];
var row = {};
row.Col1 = 'val1';
row.Col2 = 'val2';
lst.push(row);
alert(JSON.stringify(lst));​

Categories