Get Array of Object'S Keys

Get array of object's keys

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

Getting key of each object inside array of objects into an array: Javascript

Merge to a single object by spreading into Object.assign(), and then get the keys:

var obj = [{"a":1},{"b":2},{"c":3}];

const result = Object.keys(Object.assign({}, ...obj));

console.log(result);

Creating an array from object properties with Object.keys() vs Object.values()

Use .keys() if you need to do something with the keys other than to retrieve the values. Otherwise, you're only getting the keys in order to access the values, which is redundant if you can get the values directly using a different method - so, in that case, might as well use Object.values() from the beginning.

An example of where Object.keys could be useful:

const obj = {

prop1: 'val1',

prop2: 'val2'

};

const result = Object.keys(obj).map((key) => [key, obj[key]]);

console.log(result);

Find a value in an array of objects in Javascript

You can loop over the array and test for that property:

function search(nameKey, myArray){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].name === nameKey) {
return myArray[i];
}
}
}

var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];

var resultObject = search("string 1", array);

How to get all the keys of objects in an array in JavaScript

You can use the flatMap which is what you have implemented

The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map() followed by a flat() of depth 1, but flatMap() is often quite useful, as merging both into one method is slightly more efficient.

const input = [{

"a": 1,

"b": 2

}, {

"c": 3

}, {

"d": 4

}, {}, {

"e": null,

"f": 6,

"g": 7

}];

const keys = input.flatMap(Object.keys);

const values = input.flatMap(Object.values);

console.log(keys,values)

Get all keys in array of objects whose values are arrays

You could take a Set and get unique keys of the objects.

const

items = [{ name: "Joe", occupied: "no", mobile: "yes", treatment: "no", date: "29-03-2020", age: "15", stuff: ["A", "B", "C"], type: ["1", "2"] }, { name: "Jack", occupied: "yes", mobile: "no", treatment: "no", date: "02-03-2020", age: "20", stuff: ["A", "B", "C", "D", "E"], type: ["8", "6"], misc: ["otherStuff", "someStuff"] }, { name: "Jane", occupied: "no", mobile: "yes", treatment: "yes", date: "15-02-2020", age: "28", stuff: ["C", "D", "E"], type: ["4", "7"], something: ["xxx", "ccc"] }],

keys = Array.from(

items.reduce(

(s, o) => Object

.keys(o)

.reduce((t, k) => Array.isArray(o[k]) ? t.add(k) : t, s),

new Set

)

);

console.log(keys);

Find object by id in an array of JavaScript objects

Use the find() method:

myArray.find(x => x.id === '45').foo;

From MDN:

The find() method returns the first value in the array, if an element in the array satisfies the provided testing function. Otherwise undefined is returned.


If you want to find its index instead, use findIndex():

myArray.findIndex(x => x.id === '45');

From MDN:

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.


If you want to get an array of matching elements, use the filter() method instead:

myArray.filter(x => x.id === '45');

This will return an array of objects. If you want to get an array of foo properties, you can do this with the map() method:

myArray.filter(x => x.id === '45').map(x => x.foo);

Side note: methods like find() or filter(), and arrow functions are not supported by older browsers (like IE), so if you want to support these browsers, you should transpile your code using Babel (with the polyfill).

how to get the object key if the object and array value matches in javascript

You can simply iterate through the array, and then attempt to fetch the [key, value] tuples returned by Object.entries(obj) whose value matches the array value. Once found, you return the key in the tuple, i.e.:

arr.map(v => Object.entries(obj).find(x => x[1] === v)[0]);

Note: If you array may contain values that are not present in the object, the code above will throw an error because .find() will return undefined. If that's the case, you need to catch cases where an invalid value is used (defensive design):

arr.map(v => {
const foundTuple = Object.entries(obj).find(x => x[1] === v);
return foundTuple ? foundTuple[0] : null;
});

See proof-of-concept below:

const obj = {
"active": 12,
"inactive": 14,
"neutral": 16
}

const arr1 = [12];
const arr2 = [12, 14];
const arr3 = [12, 16];
const invalid_arr = [12, 999];

function getKeys(obj, arr) {
return arr.map(v => {
const foundTuple = Object.entries(obj).find(x => x[1] === v);
return foundTuple ? foundTuple[0] : null;
});
}

console.log(getKeys(obj, arr1));
console.log(getKeys(obj, arr2));
console.log(getKeys(obj, arr3));
console.log(getKeys(obj, invalid_arr));


Related Topics



Leave a reply



Submit