映射功能将结果保存到对象

时间:2018-09-05 17:24:13

标签: javascript vue.js vuejs2

这就是我的回复

data: [
    {
        id: 3,
        name: "Oliver Green",
        email: "test@gmail.com",
        contacts: "09179878564"
    },
    {
        id: 2,
        name: "Orval McLaughlin",
        email: "okoch@example.org",
        contacts: "09083692343",
    }
]

我使用了map函数来获取用户ID和用户名,现在我想做的就是将所有结果保存到一个对象

data(){
    return {
        autoComplete:{},
    }
},

let vm = this;
response.data.data.map((user) =>
{
    return vm.autoComplete = { [user.id] : user.name};
});

我得到结果,但是我只得到一个结果

autoComplete:Object
    2:"Orval McLaughlin"

结果应该是

autoComplete:Object
    3: "Oliver Green"
    2: "Orval McLaughlin"

3 个答案:

答案 0 :(得分:2)

您需要从map()返回对象,而不是赋值结果。当前,您正在为每个迭代分配vm.autoComplete。完成此操作后,可以将map的输出分配给所需的变量:

let data = [
    {
        id: 3,
        name: "Oliver Green",
        email: "test@gmail.com",
        contacts: "09179878564"
    },
    {
        id: 2,
        name: "Orval McLaughlin",
        email: "okoch@example.org",
        contacts: "09083692343",
    }
]
let autoComplete = data.map((user) => {
    return { [user.id] : user.name};
});

console.log(autoComplete)

编辑:

如果要对象而不是数组,则应使用reduce(),因为map()总是返回数组:

let data = [
    {
        id: 3,
        name: "Oliver Green",
        email: "test@gmail.com",
        contacts: "09179878564"
    },
    {
        id: 2,
        name: "Orval McLaughlin",
        email: "okoch@example.org",
        contacts: "09083692343",
    }
]
let autoComplete = data.reduce((obj, user) =>{
    obj[user.id] = user.name; // this assumes user.id will be unique
    return obj
}, {});

console.log(autoComplete)

答案 1 :(得分:0)

尝试将其不包装在数组中。

response.data.data.map((user) => {
return vm.autoComplete = Object.assign(vm.autoComplete, {[user.id] : user.name}); }

答案 2 :(得分:0)

似乎每个自动完成功能都将被覆盖。

也许您可以尝试以下方法:

  data(){
      return {
          autoComplete:{},
      }
  },

  let vm = this;

  vm.autoComplete = response.data.data.map((user) => {
      return { [user.id] : user.name};
  });