2

Hi I have this javascript array from json and I want expected output below using javascript ? Can someone give some direction.

[
    [{ "Key": 7, "Value": "Tours & experiances" }],
    [{ "Key": 6, "Value": "Theatre, dance and film" }],
    [
        { "Key": 2, "Value": "Children & family" },
        { "Key": 5, "Value": "Talks, course & workshops" }
    ],
    [{ "Key": 4, "Value": "Music" }],
    [{ "Key": 9, "Value": "Sports & fitness" }],
    [
        { "Key": 3, "Value": "Eat and drink" },
        { "Key": 8, "Value": "Shopping, markets & fairs" }
    ]
]

Expected Output

[
    { "Key": 7, "Value": "Tours & experiances" },
    { "Key": 6, "Value": "Theatre, dance and film" },
    { "Key": 2, "Value": "Children & family" },
    { "Key": 5, "Value": "Talks, course & workshops" },
    { "Key": 4, "Value": "Music" },
    { "Key": 9, "Value": "Sports & fitness" },
    { "Key": 3, "Value": "Eat and drink" },
    { "Key": 8, "Value": "Shopping, markets & fairs" } 
]
sinzo
  • 119
  • 1
  • 10
  • You can use [`.flat()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) – Nick Parsons Nov 03 '20 at 13:20

2 Answers2

1

You can simply use array.flatMap():

let input = [
    [{ "Key": 7, "Value": "Tours & experiances" }],
    [{ "Key": 6, "Value": "Theatre, dance and film" }],
    [
        { "Key": 2, "Value": "Children & family" },
        { "Key": 5, "Value": "Talks, course & workshops" }
    ],
    [{ "Key": 4, "Value": "Music" }],
    [{ "Key": 9, "Value": "Sports & fitness" }],
    [
        { "Key": 3, "Value": "Eat and drink" },
        { "Key": 8, "Value": "Shopping, markets & fairs" }
    ]
];

let result = input.flatMap(x => x);

console.log(result);
mickl
  • 48,568
  • 9
  • 60
  • 89
1

Use flat to convert an infinite number of nested arrays into one array.

const data = [
  [{ "Key": 7, "Value": "Tours & experiances" }],
  [{ "Key": 6, "Value": "Theatre, dance and film" }],
  [
    { "Key": 2, "Value": "Children & family" },
    { "Key": 5, "Value": "Talks, course & workshops" }
  ],
  [{ "Key": 4, "Value": "Music" }],
  [{ "Key": 9, "Value": "Sports & fitness" }],
  [
    { "Key": 3, "Value": "Eat and drink" },
    { "Key": 8, "Value": "Shopping, markets & fairs" }
  ]
];

const result = data.flat(Infinity);
console.log(result);
Tigran Abrahamyan
  • 756
  • 1
  • 4
  • 7