简体   繁体   中英

How to add additional properties while converting array to object in javascript?

I know to convert array to object, we use

var object = Object.assign({}, array);

I get an array from multiple select input. like this

var patterns = array["pattern1", "pattern2", "pattern3"];

Then after using object.assign I get object like this.

patterns = {
  0: pattern1,
  1: pattern2,
  2: pattern3
}

I want to add more properties and values to the object values like this:

   patterns = {
   0:{
      name: pattern1,
      status: 0
   },
   1:{
      name: pattern2,
      status: 0
      }
    }

How can I achieve this?

Maybe like this:

 var patterns = ["pattern1", "pattern2", "pattern3"]; function parrern_to_objarr(_patterns){ var out = []; for(var key in _patterns){ var out_obj = {}; out_obj.name = _patterns[key]; out_obj.status = 0; /* more properties if need... */ out.push(out_obj); } return out; } console.log(parrern_to_objarr(patterns));

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