给定合并数组,使用JS将其拆分为单个数组

时间:2015-03-23 08:14:40

标签: javascript

我有一个类似

的javascript数组
[{"Employees":[{"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},{"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}],"Departments":[{"Deptid":1,"Deptname":"IT"},{"Deptid":2,"Deptname":"HR"},{"Deptid":3,"Deptname":"HW"},{"Deptid":4,"Deptname":"SW"}]}] 

我想将它拆分为(对于员工)

[{"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},{"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}] 

AND(对于部门)

[{"Deptid":1,"Deptname":"IT"},{"Deptid":2,"Deptname":"HR"},{"Deptid":3,"Deptname":"HW"},{"Deptid":4,"Deptname":"SW"}] 

我已经审核了Split array into chunks,但事实并非如此。

enter image description here

2 个答案:

答案 0 :(得分:2)

你必须这样做:

var obj = [{"Employees":[{"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},{"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}],"Departments":[{"Deptid":1,"Deptname":"IT"},{"Deptid":2,"Deptname":"HR"},{"Deptid":3,"Deptname":"HW"},{"Deptid":4,"Deptname":"SW"}]}]

var employees = obj[0].Employees
console.log(employees)
var dept = obj[0].Departments
console.log(dept)

答案 1 :(得分:1)

data[0].Employees
// employees

data[0].Departments
// departments

您的数据包含在一个单元素数组中,该数组正由[0]解包。然后,您希望的每个值都可以作为属性直接在该对象上使用。