问题 我有一个Javascript数组,并且尝试以最有效的方式仅返回与特定键匹配的key:value对。
我尝试使用Foreach循环并将每个key:value推送到新数组,但这似乎是一种效率低下的方法,而且过于复杂。
代码
initialArray = [ { friends: [],
otherFriends: [],
_id: 5c6c7132f9bf4bdab9c906ff,
user: 5c65d9438e4a834c8e85dd7d,
password: '$2b$10$LMFB6CBdwxSAfjog/Uo3t.u/G0GBtzfJnYdpvlrSNchA9.jlNOdAa',
email: 'sparky2df3dfdfdf2@gmail.com',
createdAt: 2019-02-19T21:12:18.569Z,
updatedAt: null,
online: false,
__v: 0 },
{ friends: [],
otherFriends: [],
_id: 5c6ccd6d3a0dc4e4951c2bee,
user: 5c65d9438e4a834c8e85dd7e,
password: '$2b$10$gEAbOAdKyHJfAksr5txUNOudCautRs1w/pubplQKzZ5PefhfOOEhq',
email: 'fdagssd@gmail.com',
createdAt: 2019-02-20T03:45:49.703Z,
updatedAt: null,
online: false,
__v: 0 } ]
所需数组
[
{ user: 5c65d9438e4a834c8e85dd7d },
{ user: 5c65d9438e4a834c8e85dd7e }
]
当前方法
const newArray = []
initialArray.forEach(element => {
newArray.push({key: element.user});
});
如果有人有任何令人惊奇的建议!在此先感谢:)
答案 0 :(得分:4)
您可以为user
使用destructuring assignment并映射此short hand property。
var initialArray = [{ friends: [], otherFriends: [], _id: '5c6c7132f9bf4bdab9c906ff', user: '5c65d9438e4a834c8e85dd7d', password: '$2b$10$LMFB6CBdwxSAfjog/Uo3t.u/G0GBtzfJnYdpvlrSNchA9.jlNOdAa', email: 'sparky2df3dfdfdf2@gmail.com', createdAt: '2019-02-19T21:12:18.569Z', updatedAt: null, online: false, __v: 0 }, { friends: [], otherFriends: [], _id: '5c6ccd6d3a0dc4e4951c2bee', user: '5c65d9438e4a834c8e85dd7e', password: '$2b$10$gEAbOAdKyHJfAksr5txUNOudCautRs1w/pubplQKzZ5PefhfOOEhq', email: 'fdagssd@gmail.com', createdAt: '2019-02-20T03:45:49.703Z', updatedAt: null, online: false, __v: 0 }]
newArray = initialArray.map(({ user }) => ({ user }));
console.log(newArray);
答案 1 :(得分:1)
您可以将所需的键保留在数组中,如下所示。
此示例提取两个键值。
var initialArray = [{ friends: [], otherFriends: [], _id: '5c6c7132f9bf4bdab9c906ff', user: '5c65d9438e4a834c8e85dd7d', password: '$2b$10$LMFB6CBdwxSAfjog/Uo3t.u/G0GBtzfJnYdpvlrSNchA9.jlNOdAa', email: 'sparky2df3dfdfdf2@gmail.com', createdAt: '2019-02-19T21:12:18.569Z', updatedAt: null, online: false, __v: 0 }, { friends: [], otherFriends: [], _id: '5c6ccd6d3a0dc4e4951c2bee', user: '5c65d9438e4a834c8e85dd7e', password: '$2b$10$gEAbOAdKyHJfAksr5txUNOudCautRs1w/pubplQKzZ5PefhfOOEhq', email: 'fdagssd@gmail.com', createdAt: '2019-02-20T03:45:49.703Z', updatedAt: null, online: false, __v: 0 }],
keys = ["user", "email"], // for the desired output in the question remove "email"
newArray = initialArray.map(o => keys.reduce((a, k) => Object.assign({}, a, {[k]: o[k]}), {}));
console.log(newArray);
.as-console-wrapper { min-height: 100%; }