简体   繁体   中英

map through and object in react

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?

The code you have provided is not valid. It contains an illegal return statement.

You can reach the desired solution with using eg Object.assign .

 const portArray = [1, 4], res = portArray.map(v => Object.assign({}, { label: v, value: v })); console.log(res); 

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

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

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