Given that I have an array that is return from database that contains object,
var jsObjects = [
{a: 1, b: 2},
{a: 3, b: 4, c: 66},
{a: 5, b: 6, c: 55, d: 66},
{a: 7, b: 8, c: 12, e: 15}
];
How can I get all the keys of the object? I've been using this to obtain the keys, however I notice that index 0 wont always have all the keys. Hence problem lays.
let columns = Object.keys(jsObjects[0]),
However, the first index won't always have all the columns.
My desired output:
["a", "b", "c", "d", "e"]
To access the object's keys, use the keys() method. For example, the keys() method in JavaScript is used to return a simple array's enumerable properties.
To check if all of the values in an object are equal, use the Object. values() method to get an array of the object's values and convert the array to a Set . If the Set contains a single element, then all of the values in the object are equal. Copied!
Find specific key value in array of objects using JavaScript. We are required to write a JavaScript function that takes in one such object as the first argument, and a key value pair as the second argument. The function should then search the object for the key with specified "productId" and return that.
You can retrieve each object’s keys, values, or both combined into an array. The examples below use the following object: The Object.keys () method returns an array of strings containing all of the object’s keys, sorted by order of appearance:
The Object.keys () method returns an array of strings containing all of the object’s keys, sorted by order of appearance: Here, as well as in the following examples, we pass in the object from which the data is needed as a parameter.
Javascript Object.keys() method returns array of keys on given object.It takes Object or array as argument. Syntax Object.keys(obj) It will return the keys of only those properties/methods whose enumarable property is set to true. Examples Using simple Object
Sets are good at removing duplicates:
const jsObjects = [
{a: 1, b: 2},
{a: 3, b: 4, c: 66},
{a: 5, b: 6, c: 55, d: 66},
{a: 7, b: 8, c: 12, e: 15}
];
const keys = [...new Set(jsObjects.flatMap(Object.keys))];
console.log(keys);
You could create an object with the count of the keys and get the keys from counts.
const
objects = [{ a: 1, b: 2 }, { a: 3, b: 4, c: 66 }, { a: 5, b: 6, c: 55, d: 66 }, { a: 7, b: 8, c: 12, e: 15 }],
result = Object.keys(objects.reduce((r, o) => {
Object.keys(o).forEach(k => r[k] = true);
return r;
}));
console.log(result);
You can use a Set(), which is like an array with the exception that it doesn't allow multiple occurances of elements.
var jsObjects = [
{a: 1, b: 2},
{a: 3, b: 4, c: 66},
{a: 5, b: 6, c: 55, d: 66},
{a: 7, b: 8, c: 12, e: 15}
];
var keys = new Set();
for(object of jsObjects) {
for(key in object) {
keys = keys.add(key);
}
}
for (const key of keys) {
console.log(key);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With