我有以下JSON数据。我想根据基于Department和Employee的键值对进行过滤
var data = {
"Item": [
{
"Fields": [
{
"Key": "Title",
"Value": ""
},
{
"Key":"Name",
"Value":"Phani"
},
{
"Key":"Designation",
"Value":"Software Eng"
},
{
"Key":"Salary",
"Value":""
},
{
**"Key":"Section",**
"Value":"Employee"
}], "ItemName": "Test"
},
{
"Fields": [
{
"Key": "Title",
"Value": ""
},
{
"Key": "Name",
"Value": "Raju"
},
{
"Key": "Designation",
"Value": "Software Eng"
},
{
"Key": "Salary",
"Value": ""
},
{
"Key": "Section",
"Value": "Employee"
}], "ItemName": "Test"
},
{
"Fields": [
{
"Key": "Title",
"Value": ""
},
{
"Key": "DepName",
"Value": "Finance"
},
{
"Key": "DepType",
"Value": "Money"
},
{
"Key": "Salary",
"Value": ""
},
{
"Key": "Section",
"Value": "Department"
}], "ItemName": "Test"
},
{
"Fields": [
{
"Key": "Title",
"Value": ""
},
{
"Key": "DepName",
"Value": "IT"
},
{
"Key": "DepType",
"Value": "Tech"
},
{
"Key": "Salary",
"Value": ""
},
{
"Key": "Section",
"Value": "Department"
}], "ItemName": "Test"
}
]
};
在上面的json数据中,如果你在Fields数组中观察到我有键值对 有一个名称为Section的键及其值。
我想根据Section过滤数据,比如我想列出所有员工和所有部门。对迭代感到困惑。你能帮忙吗?
我想要两个对象和输出 var emps = [] var deps = []
这样我就可以像emp [" Designation"] emp [" Name"]一样进行迭代和访问 dep [" DepName"]等
答案 0 :(得分:1)
这应该会给你一个想法:
var firstFields = data.Item[0].Fields.map(function(field){
return { key: field.Key, value: field.Value };
});
console.log(firstFields);
map()
数据并创建您喜欢的结构。
我将以一个如何区分员工和部门的示例进行更新。
更新
// filter out departments
var departments = data.Item.filter(function(item){
var section = item.Fields[item.Fields.length -1];
return section.Value === 'Department';
});
// flatten result:
deps = [];
for(var i = 0; i < departments.length; i++){
for(var j = 0; j < departments[i].Fields.length; j++){
deps.push({ key: departments[i].Fields[j].Key,
value: departments[i].Fields[j].Value })
}
}
console.dir(deps);
http://jsfiddle.net/kwpy35hg/1/
将部门作为2个数组:
var departments = data.Item.filter(function(item){
var section = item.Fields[item.Fields.length -1];
return section.Value === 'Department';
}).map(function(deps){
return deps.Fields;
});
答案 1 :(得分:1)
这样做的一种方法是:
var result = {};
data.Item.forEach(function(item){
var fields = item.Fields;
var res = {};
for(var i=0;i<fields.length;i++)
{
res[fields[i].Key] = fields[i].Value;
}
if(!result.hasOwnProperty(res.Section)){
result[res.Section] = [];
}
result[res.Section].push(res);
})
console.log(result);
O / P:
{ Employee:
[ { Title: '',
Name: 'Phani',
Designation: 'Software Eng',
Salary: '',
Section: 'Employee' },
{ Title: '',
Name: 'Raju',
Designation: 'Software Eng',
Salary: '',
Section: 'Employee' } ],
Department:
[ { Title: '',
DepName: 'Finance',
DepType: 'Money',
Salary: '',
Section: 'Department' },
{ Title: '',
DepName: 'IT',
DepType: 'Tech',
Salary: '',
Section: 'Department' } ] }
您可以将result.Employee[i].Title
和部门作为result.Department[0].Title
访问每位员工。