Reputation: 7334
i want to create an object like this using iteratio: opts = [{label:1, value:1}, {label:4, value:4}] the values inside this object are inside an array portArray = [1,4] I'm writing
const portArray = [1,4];
return {
portArray.map(value =>
({ label: value value: value }))
};
});
but it does not seem to work. I'm missing something but i dont know what. Any ideas?
Upvotes: 0
Views: 868
Reputation: 7593
You code is missing comma separating your object properties:
{
label: value, // <-- comma between properties
value: value
}
In addition, Array#map
will return a new array of containing your values mapped to objects which you can store in a local variable:
const portArray = [1,4];
const newArray = portArray.map(value =>({ label: value, value: value }));
// remember this comma :) ----------------^
Side note about implicit vs explicit return value for arrow functions:
Parenthesis around the object literal following the arrow function, they are necessary so that function's body expression is returned implicitly.
Use of explicit return statement in arrow function (notice the addition of curly braces around the function body):
const newArray = portArray.map(value => {
return {
label: value,
value: value
}
};
Upvotes: 1
Reputation: 144
The code you provided is quite confusing, but I think I got the point of your question. Since map
returns a new array, assuming you have this array: var portArray = [1,4];
you can use map like this:
function manipulateArray(data) {
return data.map((value) => {
return {label: value, value: value};
}
}
var newArray = manipulateArray(portArray);
This way newArray
will equal [{label:1, value:1}, {label:4, value:4}]
.
You should probably read map' documentation here: MDN
Upvotes: 1
Reputation: 41893
The code you have provided is not valid. It contains an illegal return
statement.
You can reach the desired solution with using e.g. Object.assign
.
const portArray = [1, 4],
res = portArray.map(v => Object.assign({}, { label: v, value: v }));
console.log(res);
Upvotes: 2