1

I'm trying to grab the nested array called platforms, but i only want the first key in there. So for the Array it should be like [{platforms: [windows], [windows]]} instead of [{platforms: [windows, osx, linux, null], [windows, null, null, null]]} Is this even achievable? I looked through .map and .filter but can't seem to just grab the first piece of the array.

Example ARRAY

[{ id: 1,
game: { position: 1},
platforms: [ 'windows', 'osx', 'linux', null ],
title: 'xxx',
user: {
  url: 'xxxx',
  name: 'xxx',
  id: 1
}
},{ id: 2,
game: { position: 2},
platforms: [ 'windows', null, null, null, ],
title: 'xxx',
user: {
  url: 'xxxx',
  name: 'xxx',
  id: 2
}
]

How can I handle this in Javascript / NodeJS

var result = body.games.filter(a=>a).reduce((acc, a) => {
    return acc.concat(a)
}, []).map(a=>a.platforms);
console.log(result);

Result = [ 'windows', 'osx', 'linux' null ], [ 'windows', null, null, null ],

1 Answer 1

1

A simple .map should do this:

function mapPlatform(data) {
  return data.map(entry => Array.isArray(entry.platforms) ? entry.platforms[0] : 'no platform data available')
}

const data = [{id:1,game:{position:1},platforms:['windows','osx','linux',null],title:'xxx',user:{url:'xxxx',name:'xxx',id:1,},},{id:2,game:{position:2},platforms:['windows',null,null,null],title:'xxx',user:{url:'xxxx',name:'xxx',id:2,},}];
console.log(mapPlatform(data));

Sign up to request clarification or add additional context in comments.

7 Comments

frustrating! I've done this before and i get TypeError: Cannot read property '0' of undefined. However using your data const it works. There must be something wrong with my json output that i'm trying to pull from.
console.log(body.games.map(entry => entry.platforms)); gives me [ [ 'windows', 'osx', 'linux' ], [ 'windows', 'osx', 'linux' ], ] But if i do platforms[0] i get undefined..
Well, the one you've added to the question is invalid, yes. It is missing a } before ].
ok any idea on how to append that to my json to make it valid? I'll mark your answer as correct regardless, as you are right!
It would be preferable to make sure that the json is valid in the first place, instead of manually fixing it - where are you reading the data from?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.