分离并将对象分配给数组中的变量

时间:2018-02-26 09:20:18

标签: javascript arrays javascript-objects

我需要循环使用以下数组:

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"是其他一些父对象的变量名。

4 个答案:

答案 0 :(得分: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);

将获得o / p as -

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

答案 1 :(得分:1)

您无法动态声明不同的变量,而是可以拥有一个对象并为其分配属性。然后,您可以使用object destructing

单独获取属性



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




答案 2 :(得分:1)

浏览器中的

varwindow对象的一部分。我们可以像这样动态分配它:

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

答案 3 :(得分:1)

您可以使用`import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class ShowTable extends JFrame{ JFrame f=new JFrame(); JTable jt=new JTable(new DefaultTableModel()); DefaultTableModel model=(DefaultTableModel)jt.getModel(); public void showdata(int count,String host,String ip,String os_name,String os_arch,String os_version,String pro_detail,String Mac_add,float disk_size,float max_memory){ System.out.println("Row :"+count); Object data[]={host,ip,os_name,os_arch,os_version,pro_detail,Mac_add,disk_size,max_memory}; if (count == 0) { model.addColumn("HOSTNAME"); model.addColumn("IP ADDRESS"); model.addColumn("OS NAME"); model.addColumn("OS ARCHITECTURE"); model.addColumn("OS VERSION"); model.addColumn("PROCESSOR DETAIL"); model.addColumn("MAC ADDRESS"); model.addColumn("HARD DISK"); model.addColumn("RAM SIZE"); model.addRow(data); } else { model.addRow(data); } jt.setBounds(30,40,200,300); jt.setFocusable(false); jt.setRowSelectionAllowed(false); JScrollPane sp=new JScrollPane(jt); f.add(sp); f.setSize(1300,100); f.setVisible(true); } public static void main(){ JScrollPane jScrollPane1; JTable jTable1; } } ` Object.assign



array.prototype.map