0

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?

1
  • You're missing a comma. ({ label: value value: value })) should be ({ label: value, value: value })). Commented Mar 24, 2017 at 15:14

3 Answers 3

2

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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 
  }
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.