简体   繁体   English

如何在 javascript 中将数组转换为 object 时添加其他属性?

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

I know to convert array to object, we use我知道将数组转换为 object,我们使用

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

I get an array from multiple select input.我从多个 select 输入中得到一个数组。 like this像这样

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

Then after using object.assign I get object like this.然后在使用object.assign之后,我得到 object 像这样。

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

I want to add more properties and values to the object values like this:我想向 object 值添加更多属性和值,如下所示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 javascript 中检查和添加属性到数组 object - how to check and add properties to array object in javascript 如何在JavaScript中将数组中的元素添加为对象的属性 - How to add elements in an array as properties of an object in JavaScript 如何对数组进行重复数据删除,并根据其重复向数组的每个 object 添加其他属性 - How can I de-dupe an array, and add additional properties to each object of the array based on its duplications 在 mongoose 中使用.populate() 时如何获取和添加具有附加属性的 ObjectIds 到数组(由.populate() 返回),其文档在 - While using .populate() in mongoose how to fetch and add, ObjectIds with additional properties to array(returned by .populate()) whose document in javascript 如何在不删除数组现有属性的情况下向循环内的数组坐标添加其他属性 - javascript how can I add additional properties to an array's coordinates inside of a loop, without erasing the existing properties of the array 如何动态地向javascript数组中的每个对象添加属性 - How to add properties dynamically to each object in an javascript array 如何在JavaScript中将对象属性添加到数组中? - How do I add object properties into an array in JavaScript? 根据条件javascript将其他对象键添加到数组中 - Add additional object keys into array based on condition javascript Javascript,如何将 object 添加到数组中,如果数组中不存在此 object 的某些属性 - Javascript, how to add an object to an array, if some properties of this object dont already exist in the array 将对象属性转换为对象数组 - Converting object properties to array of objects
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM