从对象中选择给定属性的值到数组中

时间:2016-11-09 12:08:43

标签: javascript arrays object lodash

我有一个对象:

person = { 
    birth_year: 1970, 
    first_name: "John", 
    last_name: "Doe", 
    occupation: "Doctor", 
    city: "Boston",
    married: true 
}

我按给定顺序拥有一系列键名:

keys = ["occupation", "last_name", "city"]

我想得到这个数组:

["Doctor", "Doe", "Boston"]

重要的是,答案应该保证顺序(JavaScript不保证对象迭代的顺序)。

我认为lodash / underscore中可能有一些实用功能可以简单地完成它,但不能弄明白。

2 个答案:

答案 0 :(得分:4)

您可以使用Array.prototype.map。映射循环遍历数组并通过将函数应用于每个项目来创建新数组。当您使用keys数组作为起点,并返回该键的o中的值时,您将获得一个只包含值的新数组。

使用“动态”键名称时,使用object[stringKeyName]表示法来检索值。

var o = { 
    birth_year: 1970, 
    first_name: "John", 
    last_name: "Doe", 
    occupation: "Doctor", 
    city: "Boston",
    married: true 
};

var keys = ["occupation", "last_name", "city"];

var result = keys.map(function(k) { return o[k]; });

console.log(result);

如果它符合您的风格,您可以创建一个帮助方法来替换匿名函数:

var o = { birth_year: 1970, first_name: "John", last_name: "Doe", occupation: "Doctor", city: "Boston", married: true };
var keys = ["occupation", "last_name", "city"];

var prop = obj => key => obj[key];
var result = keys.map(prop(o));

console.log(result);

答案 1 :(得分:4)

使用Lodash,您可以使用pickvalues



var o = {
  birth_year: 1970,
  first_name: "John",
  last_name: "Doe",
  occupation: "Doctor",
  city: "Boston",
  married: true
}
var keys = ["occupation", "last_name", "city"];

var result = _.values(_.pick(o, keys));
console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
&#13;
&#13;
&#13;