Re: Stripping [ ] from JSON arrays
Elhwen Dico <[email protected]> Wed, 11 Jan 2023 17:09:27 +0100
| Newsgroups | comp.lang.php,comp.lang.javascript |
|---|---|
| Organization | Guest of ProXad - France |
| Message-ID | <[email protected]> |
Le 10/01/2023 à 05:29, JJ a écrit :
> On Tue, 10 Jan 2023 01:17:47 -0000 (UTC), The Doctor wrote:
>>
>> How do I strip unnecessary [] ?
>
> I'd use array's `reduce()` for that. e.g.
>
> var resultObj = theArray.reduce((res, obj) => Object.assign(res, obj), {});
const array = [
[0, 1, 2], [], ["tutu"], undefined
];
const result = array.filter(
(tab) => (tab && tab.length));
console.log(result);
-> [ [ 0, 1, 2 ], [ 'tutu' ] ]
you could improve filter callback to check that array members are arrays.