EN
JavaScript - how to slice object?
1
answers
0
points
How to slice an object in JavaScript?
Let's say I have the following object:
const object = {
a: 'value_A',
b: 'value_B',
c: 'value_C'
};
How can I slice two values of it?
1 answer
0
points
You can use Object.entries()
to get subarrays of properties (keys) and values.
Depending on the case, in the example below you can see how to get subarray of keys, values or key/value pairs (entries).
Practical example:
// ONLINE-RUNNER:browser;
const object = {
a: 'value_A',
b: 'value_B',
c: 'value_C',
};
const firstTwoKeys = Object.entries(object)
.slice(0, 2)
.map((entry) => entry[0]);
const firstTwoValues = Object.entries(object)
.slice(0, 2)
.map((entry) => entry[1]);
const firstTwoEntries = Object.entries(object).slice(0, 2);
console.log(JSON.stringify(firstTwoKeys)); // [ 'a', 'b' ]
console.log(JSON.stringify(firstTwoValues)); // [ 'value_A', 'value_B' ]
console.log(JSON.stringify(firstTwoEntries)); // [ [ 'a', 'value_A' ], [ 'b', 'value_B' ] ]
References
0 comments
Add comment