簡體   English   中英

如何將數組中的對象值復制到 javascript/lodash 中的另一個空數組?

[英]How to copy object value in array to another empty array in javascript/lodash?

我有以下數組,

var users = [{_id : "qwertyuiop"}, {_id: "asdfghj1kl"}, {_id : "zxcvbnm123"}];

我的預期結果是["qwertyuiop", "asdfghj1kl", "zxcvbnm123"];

除了使用 foreach 和 push 到數組之外,我想知道還有其他方法可以得到這個結果。

提前致謝。

您可以使用pluck中lodash

var users = [{_id : "qwertyuiop"}, {_id: "asdfghj1kl"}, {_id : "zxcvbnm123"}];
_.pluck(users, '_id'); // → ["qwertyuiop", "asdfghj1kl", "zxcvbnm123"]

 var users = [{_id : "qwertyuiop"}, {_id: "asdfghj1kl"}, {_id : "zxcvbnm123"}]; console.log(_.pluck(users, '_id')); // → ["qwertyuiop", "asdfghj1kl", "zxcvbnm123"]
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.2.1/lodash.min.js"></script>

這是 vanilla javascript 最好的問題之一(除非您正在鏈接)。

users.map(({_id}) => _id) // destructuring w/ arrow fnc
---
users.map(x => x._id) // arrow fnc
---
users.map(function(x) { return x._id} ) // es5

干杯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM