-1

Object look like this:

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,
    }
}

How can I get result of [{phone: 0, name: n0}, {phone:1, name: n1} .....{phone:5, name: n5}]?

I was using .map, but gives me error of "Property 'map' does not exist on type".

Is there any fast way to write the code instead of using for() loop?

cd123
  • 13
  • 4
  • What is the finished result you are hoping to produce from this? If I know what the result should look like, I think I can build out the function you're looking for. – Brandon McConnell Feb 23 '21 at 00:39

1 Answers1

1

map and reduce are array functions, not object functions. The only way to iterate over an object without creating an array first is for...in. If you don't mind creating an array, you can use Object.entries/keys/values, then do reduce, map, forEach, for...of.

In this case, the data is in a rather silly state as objects with monotonically increasing integer keys appear to be abused as 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);
ggorlen
  • 44,755
  • 7
  • 76
  • 106