简体   繁体   中英

map function save result to an object

this is what my response looks like

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

I used the map function to get the user id and user name, now what I'm trying to do is to save all of the result to an Object

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

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

I get the result however I'm only getting one result

autoComplete:Object
    2:"Orval McLaughlin"

the result should be

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

You need to return the object from map() not the result of an assignment. You are currently assigning vm.autoComplete on each iteration. After you do this you can assign the output of map to the variable you want:

 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) 

EDIT:

If you want an object instead of an array, you should use reduce() because map() always returns an array:

 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) 

Try this for not wrapping it in array.

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

It seems the autoComplete be overwrite for each.

Maybe you can try these:

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

  let vm = this;

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

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