Iterate over Object Literal Values - javascript

I have a standard jQuery plugin set up that creates default settings at the top:
jQuery.fn.myPlugin = function(options) {
var defaults = {
starts: "0px,0px",
speed: 250, ...
};
o = $.extend(defaults, options);
}
I have another variable called numberOfObjects.
I'm trying to loop through the default variables. For each object found (from numberOfObjects) I need to duplicate the value of the variable value. So, if the numberOfObjects variable is 3, the defaults.starts should be 0px,0px > 0px,0px > 0px,0px. The & gt; is used to split values.
This is what I currently have. X represents the variable name inside defaults. Y represents the variable for the current value of x. I've gotten this far and have no clue what to do next.
for (x in defaults) { // x is defaults.x
defaults.x = defaults.x + " > y";
}

var obj = {
'foo': 1,
'bar': 2
};
for (var key in obj) {
console.log(obj[key]);
}
Or with jQuery:
$.each(obj, function(key, value) {
console.log(this, value, obj[key]);
});

You should not have to depend on jQuery for this.
Object.keys(obj).forEach(function (key) {
var value = obj[key];
// do something with key or value
});
Mozilla Developer documentation - https://developer.mozilla.org
Polyfill for old browsers
View Performance Results - https://jsperf.com

Let's setup our basic object before we get started:
const x = {
x: 1,
y: 2,
z: 3
};
We can use Object.keys(x) to return an array of all of the keys within our object.
Object.keys(x)
> ['x', 'y', 'z']
Now we able to map, filter, reduce and loop over our array and do something with that value within our object:
Object.keys(x).map(key => x[key] + 1)
> [2,3,4]
Object.keys(x).forEach(key => console.log(x[key]))
> [1,2,3]
The main take away here is that we have to use the key to access that specific value, it works but it feels a little clunky. ES2017 brings with it Object.values() which can be used as a nice shortcut for returning an array of all of the values within an Object.
Object.values(x)
> [1,2,3]
Object.values(x).map(value => value + 1)
> [2,3,4]
Object.values(x).forEach(value => console.log(value))
> [1,2,3]
You can read more about Object.values() at MDN, they also include a polyfill, should you need to support older browsers & browsers which haven't yet implemented it.
There's also Object.entries() which conveniently allows you to access the keys and the values. It returns an array containing arrays (first item being the key and the second item being the value.
Object.entries(x);
> [['x', 1], ['y', 2], ['z', 3]]
We can use de-structuring to easily get at these values:
Object.entries(x).map(([key, value]) => console.log(key, value))

To iterate over an object's values you can use a for...of loop with Object.values.
const myObj = {a: 1, b: 2}
for (let value of Object.values(myObj)) {
console.log(`value=${value}`)
}
// output:
// value=1
// value=2
If you want the key and value when iterating, you can use Object.entries.
const myObj = {a: 1, b: 2}
for (let [key, value] of Object.entries(myObj)) {
console.log(`key=${key} value=${value}`)
}
// output:
// key=a value=1
// key=b value=2

Best practice is to validate if the object attribute that is being iterated over is from the object itself and not inherited from the prototype chain. You can check this using .hasOwnProperty(): (Of course if you do want to include inherited properties just remove the if statement).
Here is the general case:
for(var index in object) {
if (object.hasOwnProperty(index)) {
var value = object[index];
// do something with object value here.
}
}
Here is the example case you mentioned where you want to create a duplicate object with the value of each key duplicated replicated according to the value of the var numberofobjects (i've added in two solutions whereby you either modify the existing object or create a new one):
// function to repeat value as a string inspired by disfated's answer here http://stackoverflow.com/questions/202605/repeat-string-javascript
function repeatValue(value, count) {
value = String(value); // change to string to be able to add " > " as in question
if (count < 1) return '';
var result = '';
while (count > 1) {
if (count & 1) result += value + " > ";
count >>= 1, value += " > " + value;
}
return result + value;
}
var numberofobjects = 3;
var newObject = {}; // for use if creating a duplicate object with the new values
for(var x in defaults) {
if (defaults.hasOwnProperty(x)) {
//use this to replace existing values
defaults[x] = repeatValue(defaults[x], numberofobjects);
//or use this to create values in the new object
newObject[x] = repeatValue(defaults[x], numberofobjects);
}
}

In your code:
for(x in defaults){
defaults.x = defaults.x + " > y";
}
You need to say defaults[x] instead of defaults.x.
x is a variable holding a string that is the key into the defaults object, and the bracket (array-style) syntax lets you use that variable to get the property. With the dot notation defaults.x is looking for a property actually called "x", the equivalent of defaults["x"].

var yourVariable = {
Bobe: 23,
Pope: 33,
Doop: 43,
Dope: 53
};
for(var keyName in yourVariable){
document.write(keyName, " : ",yourVariable[keyName]," ");
};

Taken from Mozilla:
const object1 = {
a: 'somestring',
b: 42,
c: false
};
console.log(Object.values(object1));
// expected output: Array ["somestring", 42, false]

Related

How to keep an array with objects immutable in javascript?

I want to make an array based on two arrays - "ideaList" and "endorsements" declared globally. As ideaList and endorsements are used in other parts of the program I need them to be immutable, and I thought that .map and .filter would keep this immutability.
function prepareIdeaArray(){
var preFilteredIdeas=ideaList
.filter(hasIdeaPassedControl)
.map(obj => {obj.count = endorsements
.filter(x=>x.ideaNumber===obj.ideaNumber)
.reduce((sum, x)=>sum+x.count,0);
obj.like = endorsements
.filter(x=>x.ideaNumber===obj.ideaNumber && x.who===activeUser)
.reduce((sum, x)=>sum+x.count,0)===0?false:true
obj.position = generatePosition(obj.status)
obj.description = obj.description.replace(/\n/g, '<br>')
return obj;});
preFilteredIdeas.sort(compareOn.bind(null,'count',false)).sort(compareOn.bind(null,'position',true))
return preFilteredIdeas;
}
However, when I console.log ideaList after this function has been executed, I remark that objects of the array all have the "count", "like", "position" properties with values, which proves that the array has been mutated.
I tried by using .map only, but same result.
Would you know how I could prevent ideaList to get mutated? Also I would like to avoid to use const, as I declare ideaList globally first, and then assign to it some data in another function.
You're not mutating the array itself but rather the objects that the array contains references to. .map() creates a copy of the array but the references contained in it points to the exact same objects as the original, which you've mutated by adding properties directly to them.
You need to make copies of these objects too and add the properties to these copies. A neat way to do this is to use object spread in .map() callback:
.map(({ ...obj }) => {
obj.count = endorsements
.filter(x=>x.ideaNumber===obj.ideaNumber)
...
If your environment doesn't support object spread syntax, clone the object with Object.assign():
.map(originalObj => {
const obj = Object.assign({}, originalObj);
obj.count = endorsements
.filter(x=>x.ideaNumber===obj.ideaNumber)
...
In JS, the objects are referenced. When created, in other words, you get the object variable to point to a memory location which intends to be holding a meaningful value.
var o = {foo: 'bar'}
The variable o is now point to a memory which has {foo: bar}.
var p = o;
Now the variable p too is pointing to the same memory location. So, if you change o, it will change p too.
This is what happens inside your function. Even though you use Array methods which wouldn't mutate it's values, the array elements themselves are objects which are being modified inside the functions. It creates a new array - but the elements are pointing to the same old memory locations of the objects.
var a = [{foo: 1}]; //Let's create an array
//Now create another array out of it
var b = a.map(o => {
o.foo = 2;
return o;
})
console.log(a); //{foo: 2}
One way out is to create a new object for your new array during the operation. This can be done with Object.assign or latest spread operator.
a = [{foo: 1}];
b = a.map(o => {
var p = {...o}; //Create a new object
p.foo = 2;
return p;
})
console.log(a); // {foo:1}
To help having immutability in mind you could think of your values as primitives.
1 === 2 // false
'hello' === 'world' // false
you could extend this way of thinking to non-primitives as well
[1, 2, 3] === [1, 2, 3] // false
{ username: 'hitmands' } === { username: 'hitmands' } // false
to better understand it, please have a look at MDN - Equality Comparisons and Sameness
how to force immutability?
By always returning a new instance of the given object!
Let's say we have to set the property status of a todo. In the old way we would just do:
todo.status = 'new status';
but, we could force immutability by simply copying the given object and returning a new one.
const todo = { id: 'foo', status: 'pending' };
const newTodo = Object.assign({}, todo, { status: 'completed' });
todo === newTodo // false;
todo.status // 'pending'
newTodo.status // 'completed'
coming back to your example, instead of doing obj.count = ..., we would just do:
Object.assign({}, obj, { count: ... })
// or
({ ...obj, count: /* something */ })
there are libraries that help you with the immutable pattern:
Immer
ImmutableJS
You use the freeze method supplying the object you want to make immutable.
const person = { name: "Bob", age: 26 }
Object.freeze(person)
You could use the new ES6 built-in immutability mechanisms, or you could just wrap a nice getter around your objects similar to this
var myProvider = {}
function (context)
{
function initializeMyObject()
{
return 5;
}
var myImmutableObject = initializeMyObject();
context.getImmutableObject = function()
{
// make an in-depth copy of your object.
var x = myImmutableObject
return x;
}
}(myProvider);
var x = myProvider.getImmutableObject();
This will keep your object enclosed outside of global scope, but the getter will be accessible in your global scope.
You can read more on this coding pattern here
One easy way to make "copies" of mutable objects is to stringify them into another object and then parse them back into a new array. This works for me.
function returnCopy(arrayThing) {
let str = JSON.stringify(arrayThing);
let arr = JSON.parse(str);
return arr;
}
Actually, you can use spread opreator to make the original array stay unchanged, below y is the immutable array example:
const y = [1,2,3,4,5];
function arrayRotation(arr, r, v) {
for(let i = 0; i < r; i++) {
arr = [...y]; // make array y as immutable array [1,2,3,4,5]
arr.splice(i, 0, v);
arr.pop();
console.log(`Rotation ${i+1}`, arr);
}
}
arrayRotation(y, 3, 5)
If you don't use the spread operator, the y array will get changed when loop is running time by time.
Here is the mutable array result:
const y = [1,2,3,4,5];
function arrayRotation(arr, r, v) {
for(let i = 0; i < r; i++) {
arr = y; // this is mutable, because arr and y has same memory address
arr.splice(i, 0, v);
arr.pop();
console.log(`Rotation ${i+1}`, arr);
}
}
arrayRotation(y, 3, 5)
You assign these properties in your map function, you need to change this. (Just declare an empty object instead of using your current obj)

ES6 for-of loop in map key value [duplicate]

This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed last year.
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);
});

How to iterate (keys, values) in JavaScript? [duplicate]

This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed last year.
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);
});

how to prevent adding duplicate keys to a javascript array

I found a lot of related questions with answers talking about for...in loops and using hasOwnProperty but nothing I do works properly. All I want to do is check whether or not a key exists in an array and if not, add it.
I start with an empty array then add keys as the page is scrubbed with jQuery.
Initially, I hoped that something simple like the following would work: (using generic names)
if (!array[key])
array[key] = value;
No go. Followed it up with:
for (var in array) {
if (!array.hasOwnProperty(var))
array[key] = value;
}
Also tried:
if (array.hasOwnProperty(key) == false)
array[key] = value;
None of this has worked. Either nothing is pushed to the array or what I try is no better than simply declaring array[key] = value Why is something so simple so difficult to do. Any ideas to make this work?
Generally speaking, this is better accomplished with an object instead since JavaScript doesn't really have associative arrays:
var foo = { bar: 0 };
Then use in to check for a key:
if ( !( 'bar' in foo ) ) {
foo['bar'] = 42;
}
As was rightly pointed out in the comments below, this method is useful only when your keys will be strings, or items that can be represented as strings (such as numbers).
var a = [1,2,3], b = [4,1,5,2];
b.forEach(function(value){
if (a.indexOf(value)==-1) a.push(value);
});
console.log(a);
// [1, 2, 3, 4, 5]
For more details read up on Array.indexOf.
If you want to rely on jQuery, instead use jQuery.inArray:
$.each(b,function(value){
if ($.inArray(value,a)==-1) a.push(value);
});
If all your values are simply and uniquely representable as strings, however, you should use an Object instead of an Array, for a potentially massive speed increase (as described in the answer by #JonathanSampson).
A better alternative is provided in ES6 using Sets. So, instead of declaring Arrays, it is recommended to use Sets if you need to have an array that shouldn't add duplicates.
var array = new Set();
array.add(1);
array.add(2);
array.add(3);
console.log(array);
// Prints: Set(3) {1, 2, 3}
array.add(2); // does not add any new element
console.log(array);
// Still Prints: Set(3) {1, 2, 3}
If you're already using spread...
let colors = ['red', 'orange', 'yellow'];
let moreColors = ['orange', 'green'];
let mergedColors = [...colors, ...moreColors];
and want to avoid duplicates...
let mergedColors = [...colors, ...moreColors.filter(c => !colors.includes(c)) ];
You can try this:
var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
var uniqueNames = [];
$.each(names, function(i, el){
if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});
Easiest way to find duplicate values in a JavaScript array
The logic is wrong. Consider this:
x = ["a","b","c"]
x[0] // "a"
x["0"] // "a"
0 in x // true
"0" in x // true
x.hasOwnProperty(0) // true
x.hasOwnProperty("0") // true
There is no reason to loop to check for key (or indices for arrays) existence. Now, values are a different story...
Happy coding
function check (list){
var foundRepeatingValue = false;
var newList = [];
for(i=0;i<list.length;i++){
var thisValue = list[i];
if(i>0){
if(newList.indexOf(thisValue)>-1){
foundRepeatingValue = true;
console.log("getting repeated");
return true;
}
} newList.push(thisValue);
} return false;
}
var list1 = ["dse","dfg","dse"];
check(list1);
Output:
getting repeated
true
let x = "farceus";
let y = "character";
const commonCharacters = function (string1, string2) {
let duplicateCharacter = "";
for (let i = 0; i < string1.length; i += 1) {
if (duplicateCharacter.indexOf(string1[i]) === -1) {
if (string2.indexOf(string1[i]) !== -1) {
duplicateCharacter += string1[i];
}
}
}
return [...duplicateCharacter];
};
console.log(commonCharacters(x, y));

Get array of object's keys

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

Categories

Resources