2017-08-03 161 views
2

我正在使用defiantjs来选择对象中的元素。这是我的对象:如何用xPath选择多个元素?

{ 
"name": "Retail Sales", 
"weight": 10, 
"length": 6, 
"type": "retailSales", 
"rows": [ 
    { 
    "dealerEvaluationHistoryID": 0, 
    "performanceDealerMappingDetailID": 14, 
    "month": 1, 
    "plan": 0, 
    "actual": 0, 
    "weight": 0, 
    "pelanggaranWilayah": 0 
    }, 
    { 
    "dealerEvaluationHistoryID": 0, 
    "performanceDealerMappingDetailID": 14, 
    "month": 2, 
    "plan": 0, 
    "actual": 0, 
    "weight": 0, 
    "pelanggaranWilayah": 0 
    }, 
    { 
    "dealerEvaluationHistoryID": 0, 
    "performanceDealerMappingDetailID": 14, 
    "month": 3, 
    "plan": 0, 
    "actual": 0, 
    "weight": 0, 
    "pelanggaranWilayah": 0 
    } 
] 
} 

如何在行[]中的每个对象中选择所有月份,计划,实际和重量? 想我喜欢这样的输出:

[[1,0,0,0],[2,0,0,0],[3,0,0,0]] 

我可以做//rows/month//rows/plan但不知道如何执行这两种。

回答

2

您可以使用map方法,该方法对阵列中的每个项目应用回调函数函数。

了解更多关于map方法。

let obj={ 
 
    "name": "Retail Sales", 
 
    "weight": 10, 
 
    "length": 6, 
 
    "type": "retailSales", 
 
    "rows": [ 
 
     { 
 
     "dealerEvaluationHistoryID": 0, 
 
     "performanceDealerMappingDetailID": 14, 
 
     "month": 1, 
 
     "plan": 0, 
 
     "actual": 0, 
 
     "weight": 0, 
 
     "pelanggaranWilayah": 0 
 
     }, 
 
     { 
 
     "dealerEvaluationHistoryID": 0, 
 
     "performanceDealerMappingDetailID": 14, 
 
     "month": 2, 
 
     "plan": 0, 
 
     "actual": 0, 
 
     "weight": 0, 
 
     "pelanggaranWilayah": 0 
 
     }, 
 
     { 
 
     "dealerEvaluationHistoryID": 0, 
 
     "performanceDealerMappingDetailID": 14, 
 
     "month": 3, 
 
     "plan": 0, 
 
     "actual": 0, 
 
     "weight": 0, 
 
     "pelanggaranWilayah": 0 
 
     } 
 
    ] 
 
} 
 
let array=obj.rows.map(function(row){ 
 
    return [row.month,row.plan,row.actual,row.weight]; 
 
}); 
 
console.log(JSON.stringify(array));

+1

正是我一直在寻找!将接受这个作为定时器的时候的答案:) –