Reputation: 1740
I have a response that should need to return an object with specified key and value using map
I tried
response.data.data = response.data.data.map((user) =>{
return console.log({ user.id : user.name});
});
But it gives me an error due to user.id
how can i set the key coming from response?
this is my data response
data: [
{
id: 2,
name: "Orval McLaughlin",
email: "[email protected]",
contacts: "09083692343",
created_at: "2018-09-05 15:08:54",
updated_at: "2018-09-05 15:08:54",
deleted_at: null
}
],
i am using a vue js input tag where in I need a data to bind in a prop like this
{2: Orval McLaughlin}
Upvotes: 1
Views: 10365
Reputation: 56843
It does not make sense to use return console.log(whatever)
inside your mapping function because as that will always return undefined
.map()
will create an array of undefined
entries:
let users = [{ id: 1, name: "r2d2" }]
let arr = users.map(user => console.log({ id: user.id, name: user.name}))
console.log(arr);
Instead, change your mapping function to this:
let users = [{
id: 2,
name: "Orval McLaughlin",
email: "[email protected]",
contacts: "09083692343",
created_at: "2018-09-05 15:08:54",
updated_at: "2018-09-05 15:08:54",
deleted_at: null
}]
let arr = users.map(user => ({ [user.id]: user.name }))
console.log(arr);
To create a property on an object whose property name you have in a variable propName
, use the square brackets notation:
let user = { [propName]: value }
Note that you can also access the property of an object using this notation:
console.log(user[propName]);
Upvotes: 4
Reputation: 83587
console.log()
returns undefined
, so your current solution gives an array of all undefined
s. Instead, you should return the object that you want:
response.data.data = response.data.data.map((user) =>{
return { [user.id] : user.name};
});
Note that you also need to surround the user id key with brackets in order to evaluate the variable.
Upvotes: 0
Reputation: 171698
To get results like
{2: Orval McLaughlin}
you want a computed property name:
return { [user.id] : user.name};
Note that return console.log(somValue)
always returns undefined
Upvotes: 3