从一个数组中分离和赋值给变量的对象

3
我有一个需要循环的数组,如下所示:
var arr = [{
  "id": 111,
  "wbs_name": "Mechanical",
  "parent": 'root',
}, {
  "id": 222,
  "wbs_name": "Electrical",
  "parent": 111,
}, {
  "id": 333,
  "wbs_name": "Systems",
  "parent": 111,
},]

我的输出应该像这样:
 var mechanical = {
     "id": 111,
     "wbs_name": "mechanical",
     "parent": 0,
 },

 var electrical= {
     "id": 222,
     "wbs_name": "electrical",
     "parent": mechanical,
 },

 var systems = {
     "id": 222,
     "wbs_name": "systems",
     "parent": mechanical,
 },

我已经尝试循环遍历数组并将对象推入另一个数组中,但我不知道如何同时将它们分配给变量(其中变量名为"wbs_name",而"parent"是某个其他父对象的变量名)。


3
arr.forEach( s => { window[s.wbs_name] = s; } ) - gurvinder372
@gurvinder372 这就是我要找的代码。谢谢! - user8995809
我已经添加了相同的内容作为答案。 - gurvinder372
5个回答

2

尝试这个:

var mechanical = filterList('Mechanical');
var electrical = filterList('Electrical');
var systems = filterList('Systems');
function filterList(filterBy){
    return arr.filter((ad)=>{
        return ad.wbs_name == filterBy;
    })[0];
};
console.log(mechnical);
console.log(electrical);
console.log(systems);

将得到输出结果为 -

"mechnical"= {
  id: 111, 
  wbs_name: "Mechanical", 
  parent: "root"
}

0

您无法即时声明不同的变量,但是可以拥有一个对象并分配其属性。然后,您可以使用对象解构逐个获取属性。

const root = {};

const arr = [{
   "id": 111,
   "wbs_name": "Mechanical",
   "parent": 'root',
}, {
   "id": 222,
   "wbs_name": "Electrical",
   "parent": 111,
}, {
   "id": 333,
   "wbs_name": "Systems",
   "parent": 111,
}];

arr.forEach(item => root[item.wbs_name.toLowerCase()] = Object.assign({}, item));

const { mechanical, electrical, systems } = root;
console.log(mechanical);
console.log(electrical);
console.log(systems);


0

var在浏览器中是window对象的一部分。我们可以像这样动态地进行赋值:

window['my-arbitrary-string'] = arbitrary_value

0
您可以使用 Object.assignarray.prototype.map

var arr = [
    {"id": 111, "wbs_name": "Mechanical", "parent": 'root'},
    {"id": 222, "wbs_name": "Electrical", "parent": 111},
    {"id": 333, "wbs_name": "Systems", "parent": 111}
];

var { mechanical, electrical, systems} = Object.assign({}, ...arr.map(e => { 
  var parent = arr.find(i => i.id === e.parent);  
  return { [e.wbs_name.toLowerCase()] : {...e, parent: parent ? parent.wbs_name.toLowerCase() : 0 } };
 }));
 
 console.log("mechanical: ", mechanical);
 console.log("electrical: ", electrical);
 console.log("systems: ", systems);


0
尽管不建议污染全局范围,但您可以使用以下内容。
arr.forEach( s => { window[s.wbs_name] = s; } )

这段代码将为数组中每个对象的id属性创建一个全局级别变量。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接