I have this situation in my application, one array with multiple arrays inside:
i need to convert this:
[ { "tag": [ { "key": "asdasd", "label": "asdasd" }, { "key": "ddd", "label": "ddd" }, { "key": "dwd", "label": "dwd" } ] }, { "tag": [ { "key": "wdwd", "label": "wdwd" }, { "key": "", "label": "" }, { "key": "dwdw", "label": "dwdw" }, ] } ]
to one single array like:
[ 0: {key: "...",label: "...."} 1: {key: "...",label: "...."} 2: {key: "...",label: "...."} ..... ]
It’s a react web application, so it need to be in javascript solution.
Advertisement
Answer
Use Array.flatMap
:
const result = data.flatMap(obj => obj.tag);
const data = [{ "tag": [{ "key": "asdasd", "label": "asdasd" }, { "key": "ddd", "label": "ddd" }, { "key": "dwd", "label": "dwd" } ] }, { "tag": [{ "key": "wdwd", "label": "wdwd" }, { "key": "", "label": "" }, { "key": "dwdw", "label": "dwdw" }, ] } ]; const result = data.flatMap(obj => obj.tag); console.log(result);