过滤对象数组并使用值数组获取其属性

时间:2017-06-22 01:50:13

标签: javascript arrays dictionary filter

嘿伙计们这一定看起来很重复,因为我已经质疑过这个问题已经得到了回答,但这一次有点不同。

上一个问题: My previous question which is already been answered

所以这是我的问题,我有一系列对象(人),其中包含名为' name'和' role'的属性。我有另一个名为' Jobs'的阵列。如果我使用代码示例,那就好多了。

var jobs = ['engineer','scientist','developer'];
var people = [ {name:'John', role:'engineer'},
               {name:'Jane', role:'scientist'},
               {name:'Jonathan', role:'developer'},
               {name:'Jane', role:'engineer'} ];

你可以看到具有相同属性的对象' name'可见,但角色不同。我想使用' jobs'的数组将它们提取到一个新的数组。基于他们的角色。

示例输出将是:

var peopleWithJobs = [
                      {name:'John', jobs:['engineer'] }
                      {name:'Jane', jobs:['scientist', 'engineer'] },
                      {name:'Jonathan', jobs:['developer'] } 
                     ]

如果' name'财产价值在“人”阵列上重复出现。只需获取角色并推送/附加到新阵列的人员工作属性' peopleWithJobs'。

我一直在使用地图并过滤更高阶的功能,但我对javascript还是比较新的,只是不能理解这个逻辑。

2 个答案:

答案 0 :(得分:0)



var jobs = ['engineer','scientist','developer'];
var people = [ {name:'John', role:'engineer'},
               {name:'Jane', role:'scientist'},
               {name:'Jonathan', role:'developer'},
               {name:'Jane', role:'engineer'} ];
               
var peopleWithJobs = [];

for(var x=0;x<people.length;x++) {
   if(jobs.indexOf(people[x].role) != -1) {
      var uniqueNames = peopleWithJobs.map(function(val) {
         return val.name;
      });
      if(uniqueNames.indexOf(people[x].name) == -1)
        peopleWithJobs.push({name: people[x].name, jobs: [people[x].role]});
      else {
      peopleWithJobs[uniqueNames.indexOf(people[x].name)].jobs.push(people[x].role);
      }
   }
}

console.log(peopleWithJobs);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

首次对数组进行排序时,构造新数组非常简单。在检查名称是否与以前的名称相同之后,您可以逐个将项目推送到新阵列,在这种情况下,您只将角色推送到上一个人。

&#13;
&#13;
var people = [ {name:'John', role:'engineer'},
               {name:'Jane', role:'scientist'},
               {name:'Jonathan', role:'developer'},
               {name:'Jane', role:'engineer'} ];
               
function reconstruct(arr) {

  // Sort
  var arr = arr.slice().sort(function(a,b) {
    var x = a.name.toLowerCase();
    var y = b.name.toLowerCase();
    return x < y ? -1 : x > y ? 1 : 0;
   });
   
	// Construct new array
  var newArr = []; 
  
	for (i=0; i<arr.length; i++) {
		if (arr[i-1] && (arr[i].name == arr[i-1].name)) {
			newArr[newArr.length-1].role.push(arr[i].role)
		} else {
			newArr.push({name: arr[i].name, role: [arr[i].role]});
		}
	}
  
	return newArr;
}

console.log(reconstruct(people));
&#13;
&#13;
&#13;