Home > Net >  Object of Arrays, return a new array with all name key valus [duplicate]
Object of Arrays, return a new array with all name key valus [duplicate]

Time:09-17

I am trying to return all the names from an object of arrays in to an new array just containing the names, but its not working, the if statement covers the issue of dealing with an empty array being passed here is the object, any suggestions much appreciated:-

const obj = [{
    name: "Mitch",
    age: 27,
    language: "Javascript"
  },
  {
    name: "Ant",
    age: 28,
    language: "Java"
  },
  {
    name: "Natalia",
    age: 29,
    language: "C"
  },
  {
    name: "Foluso",
    age: 26,
    language: "Ruby"
  }
];


let newArray = [];

for (let i = 0; i <= obj.length; i  ) {
  newArray.push(obj.name);
  if (obj => obj.length = 0) {
    newArray = [];
  }
}
return newArray;
}

CodePudding user response:

Here it is:

const obj = [
    { name: "Mitch", age: 27, language: "Javascript" },
    { name: "Ant", age: 28, language: "Java" },
    { name: "Natalia", age: 29, language: "C" },
    { name: "Foluso", age: 26, language: "Ruby" }
];
  
const names = obj.map(x => x.name)

console.log('names', names)

CodePudding user response:

const obj = [{
    name: "Mitch",
    age: 27,
    language: "Javascript"
  },
  {
    name: "Ant",
    age: 28,
    language: "Java"
  },
  {
    name: "Natalia",
    age: 29,
    language: "C"
  },
  {
    name: "Foluso",
    age: 26,
    language: "Ruby"
  }
];
 
let new_array_of_names = obj.map(item=>item.name)
  • Related