Accesing items with custom keys in object [duplicate] - javascript

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"]

Related

How to traverse through keys and values simultaneously in javascript (react native) [duplicate]

This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 12 months ago.
I have a dictionary that has the format of
dictionary = {0: {object}, 1:{object}, 2:{object}}
How can I iterate through this dictionary by doing something like
for ((key, value) in dictionary) {
//Do stuff where key would be 0 and value would be the object
}
tl;dr
In ECMAScript 2017, just call Object.entries(yourObj).
In ECMAScript 2015, it is possible with Maps.
In ECMAScript 5, it is not possible.
ECMAScript 2017
ECMAScript 2017 introduced a new Object.entries function. You can use this to iterate the object as you wanted.
'use strict';
const object = {'a': 1, 'b': 2, 'c' : 3};
for (const [key, value] of Object.entries(object)) {
console.log(key, value);
}
Output
a 1
b 2
c 3
ECMAScript 2015
In ECMAScript 2015, there is not Object.entries but you can use Map objects instead and iterate over them with Map.prototype.entries. Quoting the example from that page,
var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
var mapIter = myMap.entries();
console.log(mapIter.next().value); // ["0", "foo"]
console.log(mapIter.next().value); // [1, "bar"]
console.log(mapIter.next().value); // [Object, "baz"]
Or iterate with for..of, like this
'use strict';
var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
for (const entry of myMap.entries()) {
console.log(entry);
}
Output
[ '0', 'foo' ]
[ 1, 'bar' ]
[ {}, 'baz' ]
Or
for (const [key, value] of myMap.entries()) {
console.log(key, value);
}
Output
0 foo
1 bar
{} baz
ECMAScript 5:
No, it's not possible with objects.
You should either iterate with for..in, or Object.keys, like this
for (var key in dictionary) {
// check if the property/key is defined in the object itself, not in parent
if (dictionary.hasOwnProperty(key)) {
console.log(key, dictionary[key]);
}
}
Note: The if condition above is necessary only if you want to iterate over the properties which are the dictionary object's very own. Because for..in will iterate through all the inherited enumerable properties.
Or
Object.keys(dictionary).forEach(function(key) {
console.log(key, dictionary[key]);
});
Try this:
dict = {0:{1:'a'}, 1:{2:'b'}, 2:{3:'c'}}
for (var key in dict){
console.log( key, dict[key] );
}
0 Object { 1="a"}
1 Object { 2="b"}
2 Object { 3="c"}
WELCOME TO 2020 *Drools in ES6*
Theres some pretty old answers in here - take advantage of destructuring. In my opinion this is without a doubt the nicest (very readable) way to iterate an object.
const myObject = {
nick: 'cage',
phil: 'murray',
};
Object.entries(myObject).forEach(([k,v]) => {
console.log("The key: ", k)
console.log("The value: ", v)
})
Edit:
As mentioned by Lazerbeak, map allows you to cycle an object and use the key and value to make an array.
const myObject = {
nick: 'cage',
phil: 'murray',
};
const myArray = Object.entries(myObject).map(([k, v]) => {
return `The key '${k}' has a value of '${v}'`;
});
console.log(myArray);
Edit 2:
To explain what is happening in the line of code:
Object.entries(myObject).forEach(([k,v]) => {}
Object.entries() converts our object to an array of arrays:
[["nick", "cage"], ["phil", "murray"]]
Then we use forEach on the outer array:
1st loop: ["nick", "cage"]
2nd loop: ["phil", "murray"]
Then we "destructure" the value (which we know will always be an array) with ([k,v]) so k becomes the first name and v becomes the last name.
The Object.entries() method has been specified in ES2017 (and is supported in all modern browsers):
for (const [ key, value ] of Object.entries(dictionary)) {
// do something with `key` and `value`
}
Explanation:
Object.entries() takes an object like { a: 1, b: 2, c: 3 } and turns it into an array of key-value pairs: [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ].
With for ... of we can loop over the entries of the so created array.
Since we are guaranteed that each of the so iterated array items is itself a two-entry array, we can use destructuring to directly assign variables key and value to its first and second item.
Try this:
var value;
for (var key in dictionary) {
value = dictionary[key];
// your code here...
}
You can do something like this :
dictionary = {'ab': {object}, 'cd':{object}, 'ef':{object}}
var keys = Object.keys(dictionary);
for(var i = 0; i < keys.length;i++){
//keys[i] for key
//dictionary[keys[i]] for the value
}
I think the fast and easy way is
Object.entries(event).forEach(k => {
console.log("properties ... ", k[0], k[1]); });
just check the documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
using swagger-ui.js
you can do this -
_.forEach({ 'a': 1, 'b': 2 }, function(n, key) {
console.log(n, key);
});
You can use below script.
var obj={1:"a",2:"b",c:"3"};
for (var x=Object.keys(obj),i=0;i<x.length,key=x[i],value=obj[key];i++){
console.log(key,value);
}
outputs
1 a
2 b
c 3
As an improvement to the accepted answer, in order to reduce nesting, you could do this instead, provided that the key is not inherited:
for (var key in dictionary) {
if (!dictionary.hasOwnProperty(key)) {
continue;
}
console.log(key, dictionary[key]);
}
Edit: info about Object.hasOwnProperty here
You can use JavaScript forEach Loop:
myMap.forEach((value, key) => {
console.log('value: ', value);
console.log('key: ', key);
});

JavaScript object indexing - many values to one key

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);

How to get key by value in object of keys of arrays in Javascript? [duplicate]

This question already has answers here:
Dynamically get 'Key' with 'Value' in javascript
(3 answers)
Closed 3 years ago.
How to get the key from object of keys of array in java script?
var object = { "a" : [], "b" : ["S","W"] "c" : ["N","E"]}
How can i get the key by the value of "S" in java script?
Object.keys()
Object.keys() will create an array of keys for the object that is in variable object
find() will find the matching key that matches the condition. In your case, matching the toSearch text inside the array values of that key, for which you can use includes() or even indexOf(toSearch) !== -1
var object = { "a" : [], "b" : ["S","W"], "c" : ["N","E"]};
var toSearch = 'S';
var key = Object.keys(object).find((key) => object[key].includes(toSearch));
console.log(key);
You can also use another way using Object.entries() like:
var object = { "a" : [], "b" : ["S","W"], "c" : ["N","E"]};
var toSearch = 'S';
var key = (Object.entries(object).find(([key, value]) => value.includes(toSearch)) || [])[0];
console.log(key);
You can create a function and pass the object & the val. Inside the function iterate the object using for..in and check if the value contains the searched text. If so then push the key in an array & return it. This returned array will contain all the key name which have the searched text in it's value array
var object = {
"a": [],
"b": ["S", "W"],
"c": ["N", "E", "S"]
}
function getKey(obj, val) {
let keyArr = [];
for (let keys in obj) {
if (obj[keys].includes(val)) {
keyArr.push(keys)
}
}
return keyArr;
}
console.log(getKey(object, 'S'))

React - convert object into array of objects with properties

I have the following object
"data":{
"name 1":"a",
"name 2":"b",
"name 3":"b",
},
How can I convert to array of objects that will keep both the name and data "a", "b" so I can map and render compoents for each one passing in the both the name and data?
If you use a reduce function you can do the following to achieve your goal
Object.keys(data).reduce((array, key) => {
return [...array, {key: data[key]}]
}, [])
Reduce is a cool function that iterates and combine data into one single item (could be 1 object, array, integer, etc).
Object.keys() is a way to get each key from the current object and be able to iterate over each.
The solution provided by Tall Paul will work perfectly but you can also use Object.entries(). It states that
The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs, 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).
so you can try something like this
let result = Object.entries(data);
result.map((item, index)=>{
console.log('key is:- ', item[0], ' and value is:- ', item[1]);
});
you can get all the keys in the object in an array using Object.keys function and use map function to get the desired output.
This will convert to array of objects that will keep both the name and data.
var data = {
"name 1":"a",
"name 2":"b",
"name 3":"b",
}
var res = Object.keys(data).map(function(name){
var obj = {};
obj[name] = data[name];
return obj;
});
console.log(res);
js native method u can use;
var data = {
"name 1":"a",
"name 2":"b",
"name 3":"b",
};
var newObj = [...Object.values(data), ...Object.keys(data)]
console.log(newObj)

Get the first key name of a JavaScript object [duplicate]

This question already has answers here:
How to access the first property of a Javascript object?
(23 answers)
Closed 3 years ago.
Let's assume we have the following JavaScript object:
ahash = {"one": [1,2,3], "two": [4,5,6]}
Is there a function that returns the first key name for the given object?
From the example above I want to get one as a result of that function.
In Javascript you can do the following:
Object.keys(ahash)[0];
You can query the content of an object, per its array position.For instance:
let obj = {plainKey: 'plain value'};
let firstKey = Object.keys(obj)[0]; // "plainKey"
let firstValue = Object.values(obj)[0]; // "plain value"
/* or */
let [key, value] = Object.entries(obj)[0]; // ["plainKey", "plain value"]
console.log(key); // "plainKey"
console.log(value); // "plain value"
There's no such thing as the "first" key in a hash (Javascript calls them objects). They are fundamentally unordered. Do you mean just choose any single key:
for (var k in ahash) {
break
}
// k is a key in ahash.
Try this:
for (var firstKey in ahash) break;
alert(firstKey); // 'one'
If you decide to use Underscore.js you better do
_.values(ahash)[0]
to get value, or
_.keys(ahash)[0]
to get key.
With Underscore.js, you could do
_.find( {"one": [1,2,3], "two": [4,5,6]} )
It will return [1,2,3]
I use Lodash for defensive coding reasons.
In particular, there are cases where I do not know if there will or will not be any properties in the object I'm trying to get the key for.
A "fully defensive" approach with Lodash would use both keys as well as get:
const firstKey = _.get(_.keys(ahash), 0);
you can put your elements into an array and hash at the same time.
var value = [1,2,3];
ahash = {"one": value};
array.push(value);
array can be used to get values by their order and hash could be used to get values by their key. just be be carryfull when you remove and add elements.

Categories