Finding an array element name [duplicate] - javascript

If I have a JS object like:
var foo = { 'bar' : 'baz' }
If I know that foo has that basic key/value structure, but don't know the name of the key, How can I get it? for ... in? $.each()?

You would iterate inside the object with a for loop:
for(var i in foo){
alert(i); // alerts key
alert(foo[i]); //alerts key's value
}
Or
Object.keys(foo)
.forEach(function eachKey(key) {
alert(key); // alerts key
alert(foo[key]); // alerts value
});

You can access each key individually without iterating as in:
var obj = { first: 'someVal', second: 'otherVal' };
alert(Object.keys(obj)[0]); // returns first
alert(Object.keys(obj)[1]); // returns second

If you want to get all keys, ECMAScript 5 introduced Object.keys. This is only supported by newer browsers but the MDC documentation provides an alternative implementation (which also uses for...in btw):
if(!Object.keys) Object.keys = function(o){
if (o !== Object(o))
throw new TypeError('Object.keys called on non-object');
var ret=[],p;
for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p);
return ret;
}
Of course if you want both, key and value, then for...in is the only reasonable solution.

Given your Object:
var foo = { 'bar' : 'baz' }
To get bar, use:
Object.keys(foo)[0]
To get baz, use:
foo[Object.keys(foo)[0]]
Assuming a single object

This is the simplest and easy way. This is how we do this.
var obj = { 'bar' : 'baz' }
var key = Object.keys(obj)[0];
var value = obj[key];
console.log("key = ", key) // bar
console.log("value = ", value) // baz
Object.keys() is javascript method which return an array of keys when using on objects.
Object.keys(obj) // ['bar']
Now you can iterate on the objects and can access values like below-
Object.keys(obj).forEach( function(key) {
console.log(obj[key]) // baz
})

A one liner for you:
const OBJECT = {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3',
'key4': 'value4'
};
const value = 'value2';
const key = Object.keys(OBJECT)[Object.values(OBJECT).indexOf(value)];
window.console.log(key); // = key2

// iterate through key-value gracefully
const obj = { a: 5, b: 7, c: 9 };
for (const [key, value] of Object.entries(obj)) {
console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
}
Refer MDN

I was having the same problem and this is what worked
//example of an Object
var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
//How to access a single key or value
var key = Object.keys(person)[0];
var value = person[key];

best way to get key/value of object.
let obj = {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3',
'key4': 'value4'
}
Object.keys(obj).map(function(k){
console.log("key with value: "+k +" = "+obj[k])
})

I don't see anything else than for (var key in foo).

Since you mentioned $.each(), here's a handy approach that would work in jQuery 1.6+:
var foo = { key1: 'bar', key2: 'baz' };
// keys will be: ['key1', 'key2']
var keys = $.map(foo, function(item, key) {
return key;
});

The easiest way is to just use Underscore.js:
keys
_.keys(object)
Retrieve all the names of the object's properties.
_.keys({one : 1, two : 2, three : 3});
=> ["one", "two", "three"]
Yes, you need an extra library, but it's so easy!

use for each loop for accessing keys in Object or Maps in javascript
for(key in foo){
console.log(key);//for key name in your case it will be bar
console.log(foo[key]);// for key value in your case it will be baz
}
Note: you can also use
Object.keys(foo);
it will give you like this
output:
[bar];

Object.keys()
The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
var arr1 = Object.keys(obj);
Object.values()
The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
var arr2 = Object.values(obj);
For more please go here

There is no way other than for ... in. If you don't want to use that (parhaps because it's marginally inefficient to have to test hasOwnProperty on each iteration?) then use a different construct, e.g. an array of kvp's:
[{ key: 'key', value: 'value'}, ...]

Well $.each is a library construct, whereas for ... in is native js, which should be better

You can use Object.keys functionality to get the keys like:
const tempObjects={foo:"bar"}
Object.keys(tempObjects).forEach(obj=>{
console.log("Key->"+obj+ "value->"+tempObjects[obj]);
});

for showing as a string, simply use:
console.log("they are: " + JSON.stringify(foo));

If you are using AWS CloudFront Functions then this would work for you.
function handler(event) {
var response = event.response;
var headers = response.headers;
if("x-amz-meta-csp-hash" in headers){
hash=headers["x-amz-meta-csp-hash"].value;
console.log('hash is ' + hash);
}
}

Readable and simple solution:
const object1 = {
first: 'I am first',
second: 'I am second'
};
for (const [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
// expected output:
// "first: I am first"
// "second: I am second"

Related

How to get list of keys from a [key: string]: string structure in Typescript? [duplicate]

I would like to get the keys of a JavaScript object as an array, either in jQuery or pure JavaScript.
Is there a less verbose way than this?
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
for (var key in foo) {
keys.push(key);
}
Use Object.keys:
var foo = {
'alpha': 'puffin',
'beta': 'beagle'
};
var keys = Object.keys(foo);
console.log(keys) // ['alpha', 'beta']
// (or maybe some other order, keys are unordered).
This is an ES5 feature. This means it works in all modern browsers but will not work in legacy browsers.
The ES5-shim has a implementation of Object.keys you can steal
You can use jQuery's $.map.
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' },
keys = $.map(foo, function(v, i){
return i;
});
Of course, Object.keys() is the best way to get an Object's keys. If it's not available in your environment, it can be trivially shimmed using code such as in your example (except you'd need to take into account your loop will iterate over all properties up the prototype chain, unlike Object.keys()'s behaviour).
However, your example code...
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
for (var key in foo) {
keys.push(key);
}
jsFiddle.
...could be modified. You can do the assignment right in the variable part.
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [], i = 0;
for (keys[i++] in foo) {}
jsFiddle.
Of course, this behaviour is different to what Object.keys() actually does (jsFiddle). You could simply use the shim on the MDN documentation.
In case you're here looking for something to list the keys of an n-depth nested object as a flat array:
const getObjectKeys = (obj, prefix = '') => {
return Object.entries(obj).reduce((collector, [key, val]) => {
const newKeys = [ ...collector, prefix ? `${prefix}.${key}` : key ]
if (Object.prototype.toString.call(val) === '[object Object]') {
const newPrefix = prefix ? `${prefix}.${key}` : key
const otherKeys = getObjectKeys(val, newPrefix)
return [ ...newKeys, ...otherKeys ]
}
return newKeys
}, [])
}
console.log(getObjectKeys({a: 1, b: 2, c: { d: 3, e: { f: 4 }}}))
I don't know about less verbose but I was inspired to coerce the following onto one line by the one-liner request, don't know how Pythonic it is though ;)
var keys = (function(o){var ks=[]; for(var k in o) ks.push(k); return ks})(foo);
Summary
For getting all of the keys of an Object you can use Object.keys(). Object.keys() takes an object as an argument and returns an array of all the keys.
Example:
const object = {
a: 'string1',
b: 42,
c: 34
};
const keys = Object.keys(object)
console.log(keys);
console.log(keys.length) // we can easily access the total amount of properties the object has
In the above example we store an array of keys in the keys const. We then can easily access the amount of properties on the object by checking the length of the keys array.
Getting the values with: Object.values()
The complementary function of Object.keys() is Object.values(). This function takes an object as an argument and returns an array of values. For example:
const object = {
a: 'random',
b: 22,
c: true
};
console.log(Object.values(object));
Year 2022 and JavaScript still does not have a sound way to work with hashes?
This issues a warning but works:
Object.prototype.keys = function() { return Object.keys(this) }
console.log("Keys of an object: ", { a:1, b:2 }.keys() )
// Keys of an object: Array [ "a", "b" ]
// WARN: Line 8:1: Object prototype is read only, properties should not be added no-extend-native
That said, Extending Built-in Objects is Controversial.
If you decide to use Underscore.js you better do
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
_.each( foo, function( val, key ) {
keys.push(key);
});
console.log(keys);

How to access all JSON array name [duplicate]

I would like to get the keys of a JavaScript object as an array, either in jQuery or pure JavaScript.
Is there a less verbose way than this?
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
for (var key in foo) {
keys.push(key);
}
Use Object.keys:
var foo = {
'alpha': 'puffin',
'beta': 'beagle'
};
var keys = Object.keys(foo);
console.log(keys) // ['alpha', 'beta']
// (or maybe some other order, keys are unordered).
This is an ES5 feature. This means it works in all modern browsers but will not work in legacy browsers.
The ES5-shim has a implementation of Object.keys you can steal
You can use jQuery's $.map.
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' },
keys = $.map(foo, function(v, i){
return i;
});
Of course, Object.keys() is the best way to get an Object's keys. If it's not available in your environment, it can be trivially shimmed using code such as in your example (except you'd need to take into account your loop will iterate over all properties up the prototype chain, unlike Object.keys()'s behaviour).
However, your example code...
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
for (var key in foo) {
keys.push(key);
}
jsFiddle.
...could be modified. You can do the assignment right in the variable part.
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [], i = 0;
for (keys[i++] in foo) {}
jsFiddle.
Of course, this behaviour is different to what Object.keys() actually does (jsFiddle). You could simply use the shim on the MDN documentation.
In case you're here looking for something to list the keys of an n-depth nested object as a flat array:
const getObjectKeys = (obj, prefix = '') => {
return Object.entries(obj).reduce((collector, [key, val]) => {
const newKeys = [ ...collector, prefix ? `${prefix}.${key}` : key ]
if (Object.prototype.toString.call(val) === '[object Object]') {
const newPrefix = prefix ? `${prefix}.${key}` : key
const otherKeys = getObjectKeys(val, newPrefix)
return [ ...newKeys, ...otherKeys ]
}
return newKeys
}, [])
}
console.log(getObjectKeys({a: 1, b: 2, c: { d: 3, e: { f: 4 }}}))
I don't know about less verbose but I was inspired to coerce the following onto one line by the one-liner request, don't know how Pythonic it is though ;)
var keys = (function(o){var ks=[]; for(var k in o) ks.push(k); return ks})(foo);
Summary
For getting all of the keys of an Object you can use Object.keys(). Object.keys() takes an object as an argument and returns an array of all the keys.
Example:
const object = {
a: 'string1',
b: 42,
c: 34
};
const keys = Object.keys(object)
console.log(keys);
console.log(keys.length) // we can easily access the total amount of properties the object has
In the above example we store an array of keys in the keys const. We then can easily access the amount of properties on the object by checking the length of the keys array.
Getting the values with: Object.values()
The complementary function of Object.keys() is Object.values(). This function takes an object as an argument and returns an array of values. For example:
const object = {
a: 'random',
b: 22,
c: true
};
console.log(Object.values(object));
Year 2022 and JavaScript still does not have a sound way to work with hashes?
This issues a warning but works:
Object.prototype.keys = function() { return Object.keys(this) }
console.log("Keys of an object: ", { a:1, b:2 }.keys() )
// Keys of an object: Array [ "a", "b" ]
// WARN: Line 8:1: Object prototype is read only, properties should not be added no-extend-native
That said, Extending Built-in Objects is Controversial.
If you decide to use Underscore.js you better do
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
_.each( foo, function( val, key ) {
keys.push(key);
});
console.log(keys);

Basic «reflection» in JS [duplicate]

I would like to get the keys of a JavaScript object as an array, either in jQuery or pure JavaScript.
Is there a less verbose way than this?
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
for (var key in foo) {
keys.push(key);
}
Use Object.keys:
var foo = {
'alpha': 'puffin',
'beta': 'beagle'
};
var keys = Object.keys(foo);
console.log(keys) // ['alpha', 'beta']
// (or maybe some other order, keys are unordered).
This is an ES5 feature. This means it works in all modern browsers but will not work in legacy browsers.
The ES5-shim has a implementation of Object.keys you can steal
You can use jQuery's $.map.
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' },
keys = $.map(foo, function(v, i){
return i;
});
Of course, Object.keys() is the best way to get an Object's keys. If it's not available in your environment, it can be trivially shimmed using code such as in your example (except you'd need to take into account your loop will iterate over all properties up the prototype chain, unlike Object.keys()'s behaviour).
However, your example code...
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
for (var key in foo) {
keys.push(key);
}
jsFiddle.
...could be modified. You can do the assignment right in the variable part.
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [], i = 0;
for (keys[i++] in foo) {}
jsFiddle.
Of course, this behaviour is different to what Object.keys() actually does (jsFiddle). You could simply use the shim on the MDN documentation.
In case you're here looking for something to list the keys of an n-depth nested object as a flat array:
const getObjectKeys = (obj, prefix = '') => {
return Object.entries(obj).reduce((collector, [key, val]) => {
const newKeys = [ ...collector, prefix ? `${prefix}.${key}` : key ]
if (Object.prototype.toString.call(val) === '[object Object]') {
const newPrefix = prefix ? `${prefix}.${key}` : key
const otherKeys = getObjectKeys(val, newPrefix)
return [ ...newKeys, ...otherKeys ]
}
return newKeys
}, [])
}
console.log(getObjectKeys({a: 1, b: 2, c: { d: 3, e: { f: 4 }}}))
I don't know about less verbose but I was inspired to coerce the following onto one line by the one-liner request, don't know how Pythonic it is though ;)
var keys = (function(o){var ks=[]; for(var k in o) ks.push(k); return ks})(foo);
Summary
For getting all of the keys of an Object you can use Object.keys(). Object.keys() takes an object as an argument and returns an array of all the keys.
Example:
const object = {
a: 'string1',
b: 42,
c: 34
};
const keys = Object.keys(object)
console.log(keys);
console.log(keys.length) // we can easily access the total amount of properties the object has
In the above example we store an array of keys in the keys const. We then can easily access the amount of properties on the object by checking the length of the keys array.
Getting the values with: Object.values()
The complementary function of Object.keys() is Object.values(). This function takes an object as an argument and returns an array of values. For example:
const object = {
a: 'random',
b: 22,
c: true
};
console.log(Object.values(object));
Year 2022 and JavaScript still does not have a sound way to work with hashes?
This issues a warning but works:
Object.prototype.keys = function() { return Object.keys(this) }
console.log("Keys of an object: ", { a:1, b:2 }.keys() )
// Keys of an object: Array [ "a", "b" ]
// WARN: Line 8:1: Object prototype is read only, properties should not be added no-extend-native
That said, Extending Built-in Objects is Controversial.
If you decide to use Underscore.js you better do
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
_.each( foo, function( val, key ) {
keys.push(key);
});
console.log(keys);

How do I insert a key value pair at a specific point in a key/value array in jquery/javascript?

Hope someone can help in jquery if I have a key value array object
var myArray= {};
myArray['key1'] = 'value1';
myArray['key2'] = 'value2';
myArray['key3'] = 'value3';
myArray['key5'] = 'value5';
myArray['key6'] = 'value6';
how would I insert another key value pair at a specific point?
e.g.
myArray['key4'] = 'value4';
between (or after) key2 and (or before) key3?
Thank you
There is no guaranteed order in ECMAscript Objects, hence, there is no way to insert a new key/value pair at a certain point.
Use an Array instead.
var arr = ['value1', 'value2', 'value3', 'value4', 'value5', 'value6'];
arr.splice(2, 0, 'new value');
console.log( arr ); // ['value1', 'value2', 'new value' 'value3', 'value4', 'value5', 'value6'];
What you have is an object ({}), not an array ([]). Keys in objects don't have a guaranteed ordering, so you can't insert one at a specific point; they're just properties of that object.
Thanks for the input. I was hoping their was an equivalent to splice for objects that I had missed. Obviously not so I resorted to good old map and rebuild.
function objectInsertafterkey(object, newKey, newVal, insertAfterkey){
newObject={};
$.map(object, function(value, key) {
if(key == insertAfterkey){
newObject[key] = value;
newObject[newKey] = newVal;
}
else
{
newObject[key] = value;
}
});
return newObject;
}
If their is a better way to insert into objects feel free to let me know.
do like this,use object:
var myArray = {key1: value1, key2: value2};
add new:
myArray.key3 = "value3";
This may help you:
the arr.splice will add a new value to existing array
http://www.w3schools.com/jsref/jsref_splice.asp
As jAndy says, if you want a specific order, use arrays.
Alternatively, you can sort the keys before use if they have sortable names (like in your example).

How to get the key of a key/value JavaScript object

If I have a JS object like:
var foo = { 'bar' : 'baz' }
If I know that foo has that basic key/value structure, but don't know the name of the key, How can I get it? for ... in? $.each()?
You would iterate inside the object with a for loop:
for(var i in foo){
alert(i); // alerts key
alert(foo[i]); //alerts key's value
}
Or
Object.keys(foo)
.forEach(function eachKey(key) {
alert(key); // alerts key
alert(foo[key]); // alerts value
});
You can access each key individually without iterating as in:
var obj = { first: 'someVal', second: 'otherVal' };
alert(Object.keys(obj)[0]); // returns first
alert(Object.keys(obj)[1]); // returns second
If you want to get all keys, ECMAScript 5 introduced Object.keys. This is only supported by newer browsers but the MDC documentation provides an alternative implementation (which also uses for...in btw):
if(!Object.keys) Object.keys = function(o){
if (o !== Object(o))
throw new TypeError('Object.keys called on non-object');
var ret=[],p;
for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p);
return ret;
}
Of course if you want both, key and value, then for...in is the only reasonable solution.
Given your Object:
var foo = { 'bar' : 'baz' }
To get bar, use:
Object.keys(foo)[0]
To get baz, use:
foo[Object.keys(foo)[0]]
Assuming a single object
This is the simplest and easy way. This is how we do this.
var obj = { 'bar' : 'baz' }
var key = Object.keys(obj)[0];
var value = obj[key];
console.log("key = ", key) // bar
console.log("value = ", value) // baz
Object.keys() is javascript method which return an array of keys when using on objects.
Object.keys(obj) // ['bar']
Now you can iterate on the objects and can access values like below-
Object.keys(obj).forEach( function(key) {
console.log(obj[key]) // baz
})
A one liner for you:
const OBJECT = {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3',
'key4': 'value4'
};
const value = 'value2';
const key = Object.keys(OBJECT)[Object.values(OBJECT).indexOf(value)];
window.console.log(key); // = key2
// iterate through key-value gracefully
const obj = { a: 5, b: 7, c: 9 };
for (const [key, value] of Object.entries(obj)) {
console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
}
Refer MDN
I was having the same problem and this is what worked
//example of an Object
var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
//How to access a single key or value
var key = Object.keys(person)[0];
var value = person[key];
best way to get key/value of object.
let obj = {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3',
'key4': 'value4'
}
Object.keys(obj).map(function(k){
console.log("key with value: "+k +" = "+obj[k])
})
I don't see anything else than for (var key in foo).
Since you mentioned $.each(), here's a handy approach that would work in jQuery 1.6+:
var foo = { key1: 'bar', key2: 'baz' };
// keys will be: ['key1', 'key2']
var keys = $.map(foo, function(item, key) {
return key;
});
The easiest way is to just use Underscore.js:
keys
_.keys(object)
Retrieve all the names of the object's properties.
_.keys({one : 1, two : 2, three : 3});
=> ["one", "two", "three"]
Yes, you need an extra library, but it's so easy!
use for each loop for accessing keys in Object or Maps in javascript
for(key in foo){
console.log(key);//for key name in your case it will be bar
console.log(foo[key]);// for key value in your case it will be baz
}
Note: you can also use
Object.keys(foo);
it will give you like this
output:
[bar];
Object.keys()
The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
var arr1 = Object.keys(obj);
Object.values()
The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
var arr2 = Object.values(obj);
For more please go here
There is no way other than for ... in. If you don't want to use that (parhaps because it's marginally inefficient to have to test hasOwnProperty on each iteration?) then use a different construct, e.g. an array of kvp's:
[{ key: 'key', value: 'value'}, ...]
Well $.each is a library construct, whereas for ... in is native js, which should be better
You can use Object.keys functionality to get the keys like:
const tempObjects={foo:"bar"}
Object.keys(tempObjects).forEach(obj=>{
console.log("Key->"+obj+ "value->"+tempObjects[obj]);
});
for showing as a string, simply use:
console.log("they are: " + JSON.stringify(foo));
If you are using AWS CloudFront Functions then this would work for you.
function handler(event) {
var response = event.response;
var headers = response.headers;
if("x-amz-meta-csp-hash" in headers){
hash=headers["x-amz-meta-csp-hash"].value;
console.log('hash is ' + hash);
}
}
Readable and simple solution:
const object1 = {
first: 'I am first',
second: 'I am second'
};
for (const [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
// expected output:
// "first: I am first"
// "second: I am second"

Categories