Javascript object list to array

# Converting Object to an Array

Long long ago, in a far far galaxy, looping over Objects was not so easy. Okay, I’m exaggerating a bit 😅. But I remember whenever I needed to convert an object into an array , I had to do something like this.

var numbers =  one: 1, two: 2, >; var keys = []; for (var number in numbers)  if (numbers.hasOwnProperty(number))  keys.push(number); > > keys; // [ 'one', 'two' ] 

I always was so angry and wished there was a better way.

# ES6 — Object.keys

And then ES6 happened! My life changed! We finally have an easier way 🥳

Now, there was a built-in method that quickly turns all the keys in my object into an array:

const numbers =  one: 1, two: 2, >; Object.keys(numbers); // [ 'one', 'two' ] 

Life was beautiful! But then I became angry again. Why can I only extract the keys, I want my values too! Humans always want more don’t we 😂 And then ES2017 rolled in.

# Object.values

Hi, I’m ES2017 and I grant you all your wish 🧞‍♀️. you can now easily extract the values into an array with one method.

const numbers =  one: 1, two: 2, >; Object.values(numbers); // [ 1, 2 ] 

# Object.entries

But ES2017 didn’t stop there. It gave me more! I grant you BOTH keys and values now, so stop being angry. I was blown away. It turned my frown upside down 😆

const numbers =  one: 1, two: 2, >; Object.entries(numbers); // [ ['one', 1], ['two', 2] ] 

# Object.entries + Destructuring

But then I’m like. nested array 🤨. C’mon, that’s not fun to work with. ES6 swoops in and like, don’t worry! That’s why I gave you destructuring!

const numbers =  one: 1, >; const objectArray = Object.entries(numbers); objectArray.forEach(([key, value]) =>  console.log(key); // 'one' console.log(value); // 1 >); 

ES6, that’s why you are simply the best 💛

# End of story

Hope you enjoyed my code story-telling time 😂

Now go out there and have some fun with all these amazing Object methods 😊

# Browser Support

Object.keys has the best support. When I say best, it means it supports Internet Explorer 😆. The other, Object.values and Object.entries , unfortunately, don’t support Internet Explorer. Luckily, polyfill exists which can improve support.

# But wait, there’s more.

Your next question might be, now how do I convert the array back to an object. Don’t worry, that’s covered. There is a new method called Object.fromEntries . It essentially is the opposite of Object.entries .

const array = [ ['one', 1], ['two', 2], ]; Object.fromEntries(array); // 

Note: This is extremely new, so support will be limited. Keep this in your knowledge box, but maybe wait a bit longer before you put it in your actual toolbox 🧰

Источник

7 ways to convert Objects into Array in JavaScript

Two days ago I tried to slice an object but later I have to convert it into an array. Therefore I am going to explain several ways to convert a JavaScript object into an array.

How to use Object.entries()?

The first method to convert a JavaScript object into an array is using Object.entries() .

Object.entries() is a method available on all JavaScript objects that returns an array of arrays, where each inner array consists of a key/value pair from the object. Here’s an example of using Object.entries() to convert an object into an array

let obj =  name: 'John', age: 30, city: 'New York' >; let arr = Object.entries(obj); console.log(arr); // Output: [['name', 'John'], ['age', 30], ['city', 'New York']] 

How to use Object.values()?

The second method to convert a JavaScript object into an array is using Object.values() .

Object.values() is a method available on all JavaScript objects that returns an array of the object’s values. Here’s an example of using Object.values() to convert an object into an array

let obj =  name: 'John', age: 30, city: 'New York' >; let arr = Object.values(obj); console.log(arr); // Output: ['John', 30, 'New York'] 

Using for. in loop with Objects

The for. in loop is a traditional looping method in JavaScript to iterate over the properties (keys) of an object. It can be used to convert an object into an array by extracting its values and forming a new array with them. Here’s an example

let obj = a: 1, b: 2, c: 3>; let arr = []; for (let key in obj)  arr.push(obj[key]); > console.log(arr); // Output: [1, 2, 3] 

Using Object.keys() and map()

The fourth method to convert a JavaScript object into an array is by using the Object.keys() method combined with the map() method.

The Object.keys() method returns an array of the properties (keys) of an object, and the map() method allows you to transform each item in an array and return a new array.

Here’s an example to use it,

let obj = a: 1, b: 2, c: 3>; let arr = Object.keys(obj).map(key => obj[key]); console.log(arr); // Output: [1, 2, 3] 

Array.from() is best method

To convert a JavaScript object into an array is by using the Array.from() method. The Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object. Here is how

let obj = a: 1, b: 2, c: 3>; let arr = Array.from(Object.entries(obj), ([key, value]) => value); console.log(arr); // Output: [1, 2, 3] 

How spread operator help to convert an Object into an Array

The second last method to convert a JavaScript object into an array is by using the spread operator ( . ). The spread operator allows you to spread the elements of an iterable such as an object, into a new array.

let obj = a: 1, b: 2, c: 3>; let arr = [. Object.values(obj)]; console.log(arr); // Output: [1, 2, 3] 

What JSON.parse() and JSON.stringify() can do

I am also learning it. I will add an example here later.

A developer lives in a state of learning, some times he suffers from imposter syndrome. I am also a developer and learner. I wrote about what I learned. I want to get you out of syndrome. Here is the newsletter that will help you to learn new concepts. Here you go

I am open to feedback, suggestion, and improvements. Thanks for your precious time.

Источник

Javascript object list to array

Last updated: Jan 7, 2023
Reading time · 4 min

banner

# Convert an Array of Objects to an Array of Values in JS

To convert an array of objects to an array of values:

  1. Use the Array.map() method to iterate over the array.
  2. On each iteration, return the value.
  3. The map() method will return a new array containing the values.
Copied!
const arrOfObj = [ id: 1, name: 'Alice'>, id: 2, name: 'Bob'>, ]; const arr = arrOfObj.map(object => object.name); console.log(arr); // 👉️ ['Alice', 'Bob']

The function we passed to the Array.map() method gets called with each element (object) in the array.

On each iteration, we access a specific property in the object to get an array of values.

The map() method returns a new array containing the values returned from the callback function.

We used an implicit return in the examples, but you can also use a function with a body and explicit return.

Copied!
const arr = [ id: 1, name: 'Alice'>, id: 2, name: 'Bob'>, id: 3, name: 'Carl'>, ]; const ids = arr.map(obj => return obj.id; >); console.log(ids); // 👉️ [1, 2, 3]

You can also use destructuring assignment to only get the necessary values.

Copied!
const arr = [ id: 1, name: 'Alice' >, id: 2, name: 'Bob' >, id: 3, name: 'Carl' >, ]; // 👇️ destructuring const ids = arr.map(( id >) => return id; >); console.log(ids); // 👉️ [1, 2, 3]

We destructured the id property in the example.

An easy way to think about destructuring is that we are taking properties from the object and assigning their values to variables.

Copied!
const id, name > = id: 1, name: 'Alice' >; console.log(id); // 👉️ 1 console.log(name); // 👉️ "Alice"

# Dealing with missing properties

If the property you are accessing is not defined on some of the objects in the array, you will get undefined values in the new array.

Copied!
const arr = [ id: 1, name: 'Alice' >, id: 2 >, id: 3, name: 'Carl' > ]; const names = arr.map((obj) => obj.name); console.log(names); // 👉️ ['Alice', undefined, 'Carl']

You can use the filter() method to remove the undefined values from the array.

Copied!
const arr = [ id: 1, name: 'Alice' >, id: 2 >, id: 3, name: 'Carl' >]; const names = arr .map((obj) => obj.name) .filter((value) => return value !== undefined; >); console.log(names); // 👉️ ['Alice', 'Carl']

The function we passed to the Array.filter method gets called with each element in the array.

The filter() method returns a new array that only contains the elements that meet the condition.

This way you can be sure the array won’t contain any undefined values.

An alternative approach is to use the Array.forEach() method to iterate over the array.

# Convert an Array of Objects to an Array of Values using forEach()

This is a three-step process:

  1. Declare a new variable and set it to an empty array.
  2. Use the Array.forEach() method to iterate over the array.
  3. On each iteration, push the current value into the new array.
Copied!
const arrOfObj = [ id: 1, name: 'Alice'>, id: 2, name: 'Bob'>, ]; const arr = []; arrOfObj.forEach(object => arr.push(object.name); >); console.log(arr); // 👉️ ['Alice', 'Bob']

The function we passed to the Array.forEach method gets called with each element (object) in the array.

The forEach() method returns undefined , so we have to declare a variable that will store the state from iterating over the array.

The last step is to push the values into the new array.

Which approach you pick is a matter of personal preference. The Array.map() method is more direct and concise.

When using forEach() , we have to declare an intermediate variable to store the state from looping over the array.

# Convert an Array of Objects to an Array of Values using for. of

This is a three-step process:

  1. Declare a new variable and initialize it to an empty array.
  2. Use a for. of loop to iterate over the array.
  3. On each iteration, push the current value into the new array
Copied!
const arrOfObj = [ id: 1, name: 'Alice'>, id: 2, name: 'Bob'>, ]; const arr = []; for (const object of arrOfObj) arr.push(object.name); > console.log(arr); // 👉️ ['Alice', 'Bob']

The for. of statement is used to loop over iterable objects like arrays, strings, Map , Set and NodeList objects and generators .

On each iteration, we access the specific property and push its value into the new array.

# Convert an Array of Objects to an Array of Values using for

You can also use a basic for loop to convert an array of objects to an array.

Copied!
const arrayOfObjects = [ id: 1, name: 'Alice'>, id: 2, name: 'Bob'>, ]; const arr = []; for (let index = 0; index arrayOfObjects.length; index++) arr.push(arrayOfObjects[index].name); > console.log(arr); // 👉️ ['Alice', 'Bob']

The syntax of a basic for loop is quite verbose and involves working with the index of the current iteration.

Which approach you pick is a matter of personal preference. I’d use the Array.map() method because I find it quite direct and intuitive.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Convert an Object to an Array in JavaScript

Summary: in this tutorial, you will learn how to convert an object to an array using Object’s methods.

To convert an object to an array you use one of three methods: Object.keys() , Object.values() , and Object.entries() .

Note that the Object.keys() method has been available since ECMAScript 2015 or ES6, and the Object.values() and Object.entries() have been available since ECMAScript 2017.

Suppose that you have a person object as follows:

const person = < firstName: 'John', lastName: 'Doe' >; Code language: JavaScript (javascript)

To convert property’s names of the person object to an array, you use the Object.keys() method:

const propertyNames = Object.keys(person); console.log(propertyNames); Code language: JavaScript (javascript)
[ 'firstName', 'lastName' ] Code language: JSON / JSON with Comments (json)

To convert property’s values of the person object to an array, you use the Object.values() method:

const propertyValues = Object.values(person); console.log(propertyValues); Code language: JavaScript (javascript)
[ 'John', 'Doe' ] Code language: JSON / JSON with Comments (json)

To convert the enumerable string-keyed properties of an object to an array, you use the Object.entries() method. For example:

const entries = Object.entries(person); console.log(entries); Code language: JavaScript (javascript)
[ [ 'firstName', 'John' ], [ 'lastName', 'Doe' ] ]Code language: JSON / JSON with Comments (json)

Источник

Читайте также:  Python eval with import
Оцените статью