繁体   English   中英

如何使用.map/.reduce 从 object 返回 map

[英]How to use .map/.reduce from object return a map

Object 看起来像这样:

informations = {
    addresses: {
        0: {phone: 0},
        1: {phone: 1},
        2: {phone: 2},
        3: {phone: 3},
        4: {phone: 4},
        5: {phone: 5},
    },

    names: {
        0: n0,
        1: n1,
        2: n2,
        3: n3,
        4: n4,
        5: n5,
    }
}

我怎样才能得到[{phone: 0, name: n0}, {phone:1, name: n1}.....{phone:5, name: n5}]结果?

我正在使用.map ,但给了我“类型上不存在属性'映射'”的错误。

有没有什么快速的方法来编写代码而不是使用 for() 循环?

mapreduce是数组函数,而不是 object 函数。 在不首先创建数组的情况下迭代 object的唯一方法是for...in 如果你不介意创建一个数组,你可以使用Object.entries / keys / values ,然后做reducemapforEachfor...of

在这种情况下,数据位于相当愚蠢的 state 中,因为具有单调增加的 integer 键的对象似乎被滥用为 arrays。 You can convert those two objects to arrays using Object.values , then "zip" the two together using map (this assumes these arrays are the same length):

 const informations = { addresses: { 0: {phone: 0}, 1: {phone: 1}, 2: {phone: 2}, 3: {phone: 3}, 4: {phone: 4}, 5: {phone: 5}, }, names: { 0: "n0", 1: "n1", 2: "n2", 3: "n3", 4: "n4", 5: "n5", } } const addresses = Object.values(informations.addresses); const names = Object.values(informations.names); const result = addresses.map(({phone}, i) => ({ phone, name: names[i] })); console.log(result);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM