简体   繁体   中英

JavaScript objects property to array

I have the following object:

const movies = {
  1: {
    id: 1,
    name: 'Planet Earth',
  },
  2: {
    id: 2,
    name: 'Selma',
  },
  3: {
    id: 3,
    name: 'Million Dollar Baby',
  },
  4: {
    id: 4,
    name: 'Forrest Gump',
  },
  5: {
    id: 5,
    name: 'Get Out',
  },
};

Then I want an array with only the property id. To do so I've tried something like:

const moviesArray = Object.values(movies);
const idArray = moviesArray.map(movie => Object.values(movie)[0]);
console.log(idArray);

It prints idArray properly but my question is if am I missing a method to solve this problem.

You could use the id property directly:

 const movies = { 1: { id: 1, name: 'Planet Earth' }, 2: { id: 2, name: 'Selma' }, 3: { id: 3, name: 'Million Dollar Baby' }, 4: { id: 4, name: 'Forrest Gump' }, 5: { id: 5, name: 'Get Out' } }, moviesArray = Object.values(movies), idArray = moviesArray.map(movie => movie.id); console.log(idArray); 

 const movies = { 1: { id: 1, name: 'Planet Earth', }, 2: { id: 2, name: 'Selma', }, 3: { id: 3, name: 'Million Dollar Baby', }, 4: { id: 4, name: 'Forrest Gump', }, 5: { id: 5, name: 'Get Out', }, }; const moviesArray = Object.values(movies); const idArray = moviesArray.map(movie => movie.id); console.log(idArray); 

I this case, I'd be more inclined to use movie => movie.id as your mapper function, rather than movie => Object.values(movie)[0] .

The issue with your current function is that it assumes id will always happen to be the first property in the Array returned by Object.values . That happens to be true with your current function as written, but I'm not sure you can necessarily guarantee that in the general case. Directly referencing movie.id works even if the properties come in a different order. It should also be a bit faster, since you don't have to convert eaxh individual object to an Array each time.

I think there wasn't a need for using Object.values in the map part here. It would have been same without it:

 const movies = { 1: { id: 1, name: 'Planet Earth', }, 2: { id: 2, name: 'Selma', }, 3: { id: 3, name: 'Million Dollar Baby', }, 4: { id: 4, name: 'Forrest Gump', }, 5: { id: 5, name: 'Get Out', }, }; const moviesArray = Object.values(movies); const idArray = moviesArray.map(movie => movie); console.log(moviesArray); 

May be you can go with more core version. In my solution the loop will be running only once.

 const movies = { 1: { id: 1, name: 'Planet Earth', }, 2: { id: 2, name: 'Selma', }, 3: { id: 3, name: 'Million Dollar Baby', }, 4: { id: 4, name: 'Forrest Gump', }, 5: { id: 5, name: 'Get Out', }, }; const idArray = []; for (let i in movies) { idArray.push(movies[i].id); } console.log(idArray); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM