循环遍历对象并提取元素

时间:2017-02-13 11:58:57

标签: javascript reactjs

我循环遍历object以提取firstName,lastName值并返回一个包含多个对象的数组

这是期望的输出

let result = [ {firstName: 'Art', lastName: 'Blakey'},
    {firstName: 'Jimmy', lastName: 'Cobb'},
    {firstName: 'Elvin', lastName: 'Jones'},
    {firstName: 'Max', lastName: 'Roach'},
    {firstName: 'Tony', lastName: 'Williams'}];

这是源对象

src = {
_id: "QdKbM9S55qHxuT7vA"
firstname: "John"
lastname: "Doe"
},
_id: "QdKbM9S55qHxuT7vA"
firstname: "Jane"
lastname: "Doe"
},

以下是我的尝试:

let myData = [];

_handleSearch() {

  src.map((user) => {
    myData.push({
        firstname: user.firstname,
        lastname: user.lastname
    })
  })

我不确定我在这里做错了什么,结果是嵌套对象的数量与所需的输出不同

2 个答案:

答案 0 :(得分:2)

首先,您需要更改src,这是不正确的,object值应以,分隔。检查一下:

src = [{
          _id: "QdKbM9S55qHxuT7vA",
          firstname: "John",
          lastname: "Doe"
       },{
          _id: "QdKbM9S55qHxuT7vA",
          firstname: "Jane",
          lastname: "Doe"
       },{
          _id: "QdKbM9S55qHxuT7vA",
          firstname: "Jane",
          lastname: "Doe"
      }]

let result = src.map((item)=>{
      return {firstname: item.firstname, lastname: item.lastname}
})

console.log(result);

答案 1 :(得分:0)

试试这个:

let myData = [];

_handleSearch() {

  myData = src.map((user) => {
    return {
        firstname: user.firstname,
        lastname: user.lastname
    }
  })