JavaScript object indexing - many values to one key - javascript

The problem: In my script I have to generate the same piece of code several items. I wish to use a dictionary to store the key:value pairs and iterate through them. Each key has multiple values associated.
let obj = {
key1: ["val1", "val2", "val3"],
key2: ["val4", "val5", "val6"]};
In my script I want to use the individual values like this:
//Key1
some code ${val1}
some other code ${val2}
....
//Key2
some code ${val4}
some other code ${val5}
....
I can't find a way to access the individual values instead of the array associated with the key. I've tried 'indexing' ${obj[key][0] but that of course doesn't work.
Object.keys(obj).forEach((key, index) => {
console.log(`Log the key here: ${obj[key]}!`)
})

For iterating through all the values you can do something like this.
for..in loop for iterating the object and
for..of loop for iterating the array associated with each key of the object
let obj = {
key1: ["val1", "val2", "val3"],
key2: ["val4", "val5", "val6"]};
for(const x in obj){
for(const y of obj[x]) {
console.log(`Log the key here: ${y}!`)
}
}

Another option would be.
So with Object.entries we get key and value from an object, iterate and get the values.
let obj = {
key1: ["val1", "val2", "val3"],
key2: ["val4", "val5", "val6"]
};
Object.entries(obj).forEach(([key, values]) => {
values.forEach((value) => {
console.log(`some code ${key}:${value}`)
})
})

If you want to index in to obj you define in your example, here's how you can pull out 'val1' and 'val2' values.
let obj = {
key1: ["val1", "val2", "val3"],
key2: ["val4", "val5", "val6"]};
var v1 = obj['key1'][0];
var v2 = obj['key1'][1];
console.log(v1);
console.log(v2);

Related

Accesing items with custom keys in object [duplicate]

This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 1 year ago.
I have object like this:
{
"first" : "value1",
"second" : "value2"
}
I want to access both values in for cycle. Order of getting values doesn't mind. Usage is for something like value = value + "something". How to acces values which key names I don't know? Of course I can get keys from helping array like:
var keys = ["first", "second"];
And then get them by index and with them get value1 and value2 from my original array. Is there some better way? For some reason foreach doesn't work either.
Javascript has a for ... in to loop through keys
for (var key in object) {
console.log(object[key])
}
To access both values:
const data = {
"first": "value1",
"second": "value2"
};
// (1) for-loop
for (const [key, value] of Object.entries(data)) {
console.log("for-loop:", key, value);
}
// (2) Array.prototype.forEach
Object.entries(data).forEach(([key, value]) => {
console.log("Array.prototype.forEach:", key, value);
});
If you just want the keys and values separately in an array you can do the following:
var data = {
"first" : "value1",
"second" : "value2"
}
var keys = Object.keys(data)
var values = Object.values(values)
Printing them out individually would give you:
console.log(keys)
Output: ["first", "second"]
console.log(values)
Output: ["value1", "value2"]

Finding an array element name [duplicate]

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"

Filter an array for a subset of object keys

Suppose I have:
var JSONArray = [{'key1':'a1','key2':'a2','key3':'a3'},
{'key1':'b1','key2':'b2','key3':'b3'},
etc
];
How do I get an array that will hold the same objects, but without 'key3'?
underscore.js might be useful.
Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects.
var JSONArray = [
{'key1':'a1','key2':'a2','key3':'a3'},
{'key1':'b1','key2':'b2','key3':'b3'}
];
_.map(JSONArray, function (x) { return _.omit(x, 'key3') });
=> [{'key1':'a1','key2':'a2'}, {'key1':'b1','key2':'b2'}]
Working sample
Maybe using map and reduce?
var JSONArray = [{'key1':'a1','key2':'a2','key3':'a3'},
{'key1':'b1','key2':'b2','key3':'b3'}
];
JSONArray.map(function(obj){
return Object.keys(obj).reduce(function(filtered, curr){
if(curr !== 'key3'){
filtered[curr] = obj[curr];
}
return filtered;
}, {});
});
var JSONArray = [{'key1':'a1','key2':'a2','key3':'a3'},
{'key1':'b1','key2':'b2','key3':'b3'}];
1. You can remove the values from the objects in the array:
JSONArray.forEach(function(itm){
delete itm.key3;
});
new value of JSONArray:
[{"key1":"a1","key2":"a2"},{"key1":"b1","key2":"b2"}]
2. or you can clone a new array of new objects-
var nokey3=
JSON.parse(JSON.stringify(JSONArray));
nokey3.forEach(function(itm){
delete itm.key3;
});
value of JSONArray:
[{"key1":"a1","key2":"a2","key3":"a3"},
{"key1":"b1","key2":"b2","key3":"b3"}]
value of nokey3:
[{"key1":"a1","key2":"a2"},{"key1":"b1","key2":"b2"}]
You can go through the array and delete each key value pair where the key is 'key3':
for (var i = 0; i < JSONArray.length; i++) {
delete JSONArray[i]['key3'];
}
JSONArray will now be:
[
{key1: "a1", key2: "a2"},
{key1: "b1", key2: "b2"}
];

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