Languages

JavaScript - how to slice object?

0 points
Asked by:
Walter
586

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
Answered by:
Walter
586

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

  1. Object.entries() - JavaScript | MDN
  2. Array.prototype.map() - JavaScript | MDN
  3. Array.prototype.slice() - JavaScript | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join