Sorting an object? - javascript

How to sort this object lexicographically by its keys:
var obj = {'somekey_B' : 'itsvalue', 'somekey_A' : 'itsvalue');
so that it outputs like this:
for (k in obj) {
alert(k + ' : ' + obj[k]); //first "somekey_A : itsvalue"; then "somekey_B : itsvalue"
}

You can't. The order in which for..in loops through the property names is implementation-specific and cannot be controlled. Your only alternative is to organize the properties yourself in some way, such as building an array of keys and then sorting it, e.g.:
var keys, index;
keys = [];
for (k in obj) {
keys.push(k);
}
keys.sort();
for (index = 0; in dex < keys.length; ++index) {
k = keys[index];
alert(k + ' : ' + obj[k]); //first "somekey_A : itsvalue"; then "somekey_B : itsvalue"
}
You could, of course, put that in a function on the object and use it to iterate through the keys. Alternately, you could keep a sorted array on the object itself, provided you kept it up-to-date when you created new properties.

You need to copy the keys of the object into a sortable data structure, sort it, and use that in your for..in loop to reference the values.
var ob = {
foo: "foo",
bar: "bar",
baz: "baz"
};
var keys = [];
for (key in ob) {
keys.push(key);
}
keys.sort();
keys.forEach(
function (key) {
alert(ob[key]);
}
);

If the object is an arrya (or you made it an array using Prototype, jQuery, etc) you can use the native array.sort() function. You can even use your own callback function for sorting the values.

Related

How to dynamically change the key names of object properties in an array

I have an array of objects, like so:
arr = [{"timeslot":"6am7am","AVG(Monday)":10,"AVG(Tuesday)":11,"AVG(Wednesday)":7}]
Each object will always contain the "timeslot" property, and can contain any combination of the day-of-the-week properties, Monday through Sunday. Each day of the week may only be represented once in a single object.
I want to alter each object: specifically, the key names of the day-of-the-week properties only (the "timeslot" property will be unchanged"), to get an array like so:
newArr = [{"timeslot":"6am7am","Monday":10,"Tuesday":11,"Wednesday":7}]
My slightly unreadable solution works:
// Iterate the array of objects
results.forEach(function(o) {
// Iterate the object's properties
Object.keys(o).forEach(function(k) {
if(k.includes("AVG")) {
var len = k.length;
var pos = len - 1;
var newKey = k.slice(4, pos); // Extract the day of the week from the key name
o[newKey] = o[k]; // Create the new property with the same value and the new key-name
delete o[k]; // Delete the original property
}
});
});
How can I improve this solution?
Instead of mutating the original array by adding and removing keys from each object, Array#map the array into a new array, and recreate the objects using Array#reduce:
var arr = [{"timeslot":"6am7am","AVG(Monday)":10,"AVG(Tuesday)":11,"AVG(Wednesday)":7}];
var result = arr.map(function(obj) {
return Object.keys(obj).reduce(function(r, key) {
var k = key.includes('AVG') ? key.slice(4, -1) : key;
r[k] = obj[key];
return r;
}, {});
});
console.log(result);

How to get array key name using jQuery?

I have an array like this:
var myArray = new Array();
myArray['foo'] = {
Obj: {
key: value
}
};
myArray['bar'] = {
Obj: {
key: value
}
};
When I do console.log(myArray) I just get empty [ ]. And when I try to iterate the array using jQuery's each the function doesn't run.
How can I get the 'foo' and 'bar' parts of the array?
Example code:
console.log(myArray); // [ ]
jQuery.each(myArray, function(key, obj) {
console.log(key); // should be 'foo' following by 'bar'
});
In addition, why does this work:
jQuery.each(myArray[foo], function(obj, values) {
// Why does this work if there are no associative arrays in JS?
});
you can get keys by:
Object.keys(variable name);
it returns array of keys.
You need to define it as an object if you want to access it like that:
var myObj= {};
myObj.foo = ...;
myObj.bar = ...;
Now you can access the properties like myObj["bar"] or myObj.bar
Note:
To loop through all the properties it's wise to add an additional check. This is to prevent you from looping through inherited properties.
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
// Do stuff.
}
}
Array is a collection where each element has an index.
To add element to array you can use push method
myArray.push('someValue');
or set element by index (if length of array < index):
myArray.push('someValue1');
myArray.push('someValue1');
myArray[0] = 'new someValue1';
Note that array is an instance of Object class, so you can add/edit any property of this object:
myArray.foo = '1';
myArray['bar'] = '2';
In this case you will not add new element to array, you defining new properties of object.
And you don't need to create object as Array if you don't wont to use indexes.
To create new object use this code:
var myObj = {};
To get all properties of object see
How to get all properties values of a Javascript Object (without knowing the keys)?
var myArray = {};
myArray['foo'] = { 'key': 'value' }
myArray['bar'] ={ 'key': 'value' }
console.log(myArray)
jQuery.each(myArray['foo'], function(obj, values) {
console.log(obj, values)
});
Demo
With your Array of Objects you could use this function:
var getKeys = function(obj) {
if (!(typeof obj == "object")) return [];
var keys = [];
for (var key in obj) if (obj != null && hasOwnProperty.call(obj, key)) keys.push(key);
return keys;
};
getKeys(myArray) would give you an array of your Keys.
This is basically a cleared up version of underscores _.keys(myArray) function. You should consider using underscore.
// $.each() function can be used to iterate over any collection, whether it is an object or an array.
var myArray = {};
myArray['alfa'] = 0;
myArray['beta'] = 1;
$.each(myArray, function(key, value) {
alert(key);
});
Note: checkout http://api.jquery.com/jQuery.each/ for more information.

How to Loop through JavaScript object literal with objects as members in descending order

for (var key in validation_messages) {
var obj = validation_messages[key];
for (var prop in obj) {
if(obj.hasOwnProperty(prop)){
alert(prop + " = " + obj[prop]);
}
}
}
This is the for loop that i have but i'm getting the response in ascending order. But i need it in descending order. Can some one help me.
Thanks
Javascript does not guarantee a specific object property order, see this: Does JavaScript Guarantee Object Property Order?
If you need a specific order, you should use an array.
If you had them in an array, the code would look like this(fiddle:http://jsfiddle.net/DH3VQ/1/) :
var props = [
{ key:"p1", value:"a"},
{ key:"p2", value:"b"},
{ key:"p3", value:"c"},
];
for (var i = 0; i< props.length; i++){
alert(props[i].key + " = " + props[i].value);
}
Or you could do something fancier:
props.forEach(function(prop){alert(prop.key + " = " + prop.value)});
But the standard for is probably more portable.
Like this:
Object.keys(validation_messages)
.sort(function(a,b) {
return b.localeCompare(a);
})
.forEach(function(key) {
var val = validation_messages[key];
console.log(key, val);
});
Object.keys gets the enumerable properties of an object into an Array. Then the .sort() will sort them in descending order, and the .forEach() will iterate the sorted set of keys.
So then for each key, you can grab the value from the object, and use it.

Getting the first index of an object

Consider:
var object = {
foo: {},
bar: {},
baz: {}
}
How would I do this:
var first = object[0];
console.log(first);
Obviously, that doesn’t work because the first index is named foo,
not 0.
console.log(object['foo']);
works, but I don’t know it’s named foo. It could be named anything. I just want the first.
Just for fun this works in JS 1.8.5
var obj = {a: 1, b: 2, c: 3};
Object.keys(obj)[0]; // "a"
This matches the same order that you would see doing
for (o in obj) { ... }
If you want something concise try:
for (first in obj) break;
alert(first);
wrapped as a function:
function first(obj) {
for (var a in obj) return a;
}
they're not really ordered, but you can do:
var first;
for (var i in obj) {
if (obj.hasOwnProperty(i) && typeof(i) !== 'function') {
first = obj[i];
break;
}
}
the .hasOwnProperty() is important to ignore prototyped objects.
This will not give you the first one as javascript objects are unordered, however this is fine in some cases.
myObject[Object.keys(myObject)[0]]
If the order of the objects is significant, you should revise your JSON schema to store the objects in an array:
[
{"name":"foo", ...},
{"name":"bar", ...},
{"name":"baz", ...}
]
or maybe:
[
["foo", {}],
["bar", {}],
["baz", {}]
]
As Ben Alpert points out, properties of Javascript objects are unordered, and your code is broken if you expect them to enumerate in the same order that they are specified in the object literal—there is no "first" property.
for first key of object you can use
console.log(Object.keys(object)[0]);//print key's name
for value
console.log(object[Object.keys(object)[0]]);//print key's value
There is no way to get the first element, seeing as "hashes" (objects) in JavaScript have unordered properties. Your best bet is to store the keys in an array:
var keys = ["foo", "bar", "baz"];
Then use that to get the proper value:
object[keys[0]]
ES6
const [first] = Object.keys(obj)
Using underscore you can use _.pairs to get the first object entry as a key value pair as follows:
_.pairs(obj)[0]
Then the key would be available with a further [0] subscript, the value with [1]
I had the same problem yesterday. I solved it like this:
var obj = {
foo:{},
bar:{},
baz:{}
},
first = null,
key = null;
for (var key in obj) {
first = obj[key];
if(typeof(first) !== 'function') {
break;
}
}
// first is the first enumerated property, and key it's corresponding key.
Not the most elegant solution, and I am pretty sure that it may yield different results in different browsers (i.e. the specs says that enumeration is not required to enumerate the properties in the same order as they were defined). However, I only had a single property in my object so that was a non-issue. I just needed the first key.
You could do something like this:
var object = {
foo:{a:'first'},
bar:{},
baz:{}
}
function getAttributeByIndex(obj, index){
var i = 0;
for (var attr in obj){
if (index === i){
return obj[attr];
}
i++;
}
return null;
}
var first = getAttributeByIndex(object, 0); // returns the value of the
// first (0 index) attribute
// of the object ( {a:'first'} )
To get the first key of your object
const myObject = {
'foo1': { name: 'myNam1' },
'foo2': { name: 'myNam2' }
}
const result = Object.keys(myObject)[0];
// result will return 'foo1'
Based on CMS answer. I don't get the value directly, instead I take the key at its index and use this to get the value:
Object.keyAt = function(obj, index) {
var i = 0;
for (var key in obj) {
if ((index || 0) === i++) return key;
}
};
var obj = {
foo: '1st',
bar: '2nd',
baz: '3rd'
};
var key = Object.keyAt(obj, 1);
var val = obj[key];
console.log(key); // => 'bar'
console.log(val); // => '2nd'
My solution:
Object.prototype.__index = function(index)
{
var i = -1;
for (var key in this)
{
if (this.hasOwnProperty(key) && typeof(this[key])!=='function')
++i;
if (i >= index)
return this[key];
}
return null;
}
aObj = {'jack':3, 'peter':4, '5':'col', 'kk':function(){alert('hell');}, 'till':'ding'};
alert(aObj.__index(4));

How do I access properties of a javascript object if I don't know the names?

Say you have a javascript object like this:
var data = { foo: 'bar', baz: 'quux' };
You can access the properties by the property name:
var foo = data.foo;
var baz = data["baz"];
But is it possible to get these values if you don't know the name of the properties? Does the unordered nature of these properties make it impossible to tell them apart?
In my case I'm thinking specifically of a situation where a function needs to accept a series of name-value pairs, but the names of the properties may change.
My thoughts on how to do this so far is to pass the names of the properties to the function along with the data, but this feels like a hack. I would prefer to do this with introspection if possible.
You can loop through keys like this:
for (var key in data) {
console.log(key);
}
This logs "Name" and "Value".
If you have a more complex object type (not just a plain hash-like object, as in the original question), you'll want to only loop through keys that belong to the object itself, as opposed to keys on the object's prototype:
for (var key in data) {
if (data.hasOwnProperty(key)) {
console.log(key);
}
}
As you noted, keys are not guaranteed to be in any particular order. Note how this differs from the following:
for each (var value in data) {
console.log(value);
}
This example loops through values, so it would log Property Name and 0. N.B.: The for each syntax is mostly only supported in Firefox, but not in other browsers.
If your target browsers support ES5, or your site includes es5-shim.js (recommended), you can also use Object.keys:
var data = { Name: 'Property Name', Value: '0' };
console.log(Object.keys(data)); // => ["Name", "Value"]
and loop with Array.prototype.forEach:
Object.keys(data).forEach(function (key) {
console.log(data[key]);
});
// => Logs "Property Name", 0
Old versions of JavaScript (< ES5) require using a for..in loop:
for (var key in data) {
if (data.hasOwnProperty(key)) {
// do something with key
}
}
ES5 introduces Object.keys and Array#forEach which makes this a little easier:
var data = { foo: 'bar', baz: 'quux' };
Object.keys(data); // ['foo', 'baz']
Object.keys(data).map(function(key){ return data[key] }) // ['bar', 'quux']
Object.keys(data).forEach(function (key) {
// do something with data[key]
});
ES2017 introduces Object.values and Object.entries.
Object.values(data) // ['bar', 'quux']
Object.entries(data) // [['foo', 'bar'], ['baz', 'quux']]
for(var property in data) {
alert(property);
}
You often will want to examine the particular properties of an instance of an object,
without all of it's shared prototype methods and properties:
Obj.prototype.toString= function(){
var A= [];
for(var p in this){
if(this.hasOwnProperty(p)){
A[A.length]= p+'='+this[p];
}
}
return A.join(', ');
}
function getDetailedObject(inputObject) {
var detailedObject = {}, properties;
do {
properties = Object.getOwnPropertyNames( inputObject );
for (var o in properties) {
detailedObject[properties[o]] = inputObject[properties[o]];
}
} while ( inputObject = Object.getPrototypeOf( inputObject ) );
return detailedObject;
}
This will get all properties and their values (inherited or own, enumerable or not) in a new object. original object is untouched. Now new object can be traversed using
var obj = { 'b': '4' }; //example object
var detailedObject = getDetailedObject(obj);
for(var o in detailedObject) {
console.log('key: ' + o + ' value: ' + detailedObject[o]);
}
var obj = {
a: [1, 3, 4],
b: 2,
c: ['hi', 'there']
}
for(let r in obj){ //for in loop iterates all properties in an object
console.log(r) ; //print all properties in sequence
console.log(obj[r]);//print all properties values
}
You can use Object.keys(), "which returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop."
You can use any object in place of stats:
var stats = {
a: 3,
b: 6,
d: 7,
erijgolekngo: 35
}
/* this is the answer here */
for (var key in Object.keys(stats)) {
var t = Object.keys(stats)[key];
console.log(t + " value =: " + stats[t]);
}
var attr, object_information='';
for(attr in object){
//Get names and values of propertys with style (name : value)
object_information += attr + ' : ' + object[attr] + '\n';
}
alert(object_information); //Show all Object

Categories