【问题标题】:Take the property values of objects within an array out of the objects in an efficient way以有效的方式从对象中取出数组中对象的属性值
【发布时间】:2017-10-31 10:58:47
【问题描述】:

我有一个数组,其中包含这样的服务器返回的对象:

myArr = [{
    "id": 1
}, {
    "id": 2
}, {
    "id": 3
}, {
    "id": 4
}, {
    "id": 5
}, {
     "id": 6
}, {
    "id": 7
}, {
    "id": 8
}, {
    "id": 9
}, {
    "id": 10
}];

我需要变成这样:

myArr = [
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10
];

我当然可以遍历数组,比如:

// array to hold property values
let myNewArr = [];

// loop through the objects and take the value of id of each object
for (let i = 0; i < myArr.length; ++i) {
    myNewArr.push(myArr[i].id);
}

有没有更有效的方法来做到这一点,最好使用 Lodash?我不想在代码中添加另一个循环,因为它已经充满了循环。

【问题讨论】:

    标签: javascript arrays javascript-objects


    【解决方案1】:

    数组映射就是你要找的:

    myArr.map(function(x){ return x.id; })
    

    它会自动循环你的数组并“提取”你内部对象的 id 值,返回一个数组。

    【讨论】:

    • 谢谢!不过,我接受了 Hussain 的回答,因为他使用了 Lodash(它使我的代码与我正在处理的其他代码更相似)。
    【解决方案2】:

    用lodash:

    let myArr = _.map(myArr, (b) => b.id);
    

    带箭头操作符:

    let d = myArr.map(b => b.id);
    

    【讨论】:

    • 谢谢这是完美的:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2018-11-02
    • 2011-05-27
    • 2018-11-14
    • 2021-10-01
    • 2017-07-23
    相关资源
    最近更新 更多