gpt4 book ai didi

javascript - 从对象中选取给定属性的值到数组中

转载 作者:行者123 更新时间:2023-11-30 07:21:27 26 4
gpt4 key购买 nike

我有一个对象:

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 中可能有一些实用函数可以简单地做到这一点,但无法弄清楚。

最佳答案

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>

关于javascript - 从对象中选取给定属性的值到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40506682/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com