skip to Main Content
debug: {ping: true, query: false, srv: false, querymismatch: false, ipinsrv: false, …}

eula_blocked: false
ip: "45.146.253.38"
online: true
players: {online: 0, max: 20}
port: 2018
version: "1.20.1"

I want to filter out online: 0and max: 20using javascript.
(The array is stored in a variable and comes from an api)

EDIT: I found a way to filter the values out, but it somehow only works if I manually input my data, and not if I use the data from the variable of the API response…

const data = {
    players:{online: 0,max: 20}
}

console.log("")
console.log("players online:", data.players.online)
console.log("players max:   ", data.players.max)

This works with the const data but not with the actual variable I want to work with, altough it has the same structure. Why is that?

2

Answers


  1. The Array.filter is going to return the elements that follows an logic, for example [1,2,3].filter(num => num < 2) will return [1] so If you want a new array with the objects that have the properties online = 0 and max = 20 you should go for:

    array.filter(item => {
      return item.players.online === 0 && item.players.max === 20;
    }
    
    Login or Signup to reply.
  2. const responseData = [
      {
        debug: { ping: true, query: false, srv: false, querymismatch: false, ipinsrv: false },
        eula_blocked: false,
        ip: "45.146.253.38",
        online: true,
        players: { online: 0, max: 20 },
        port: 2018,
        version: "1.20.1",
      },
      // Add more objects here if there are multiple data points
      // {
      //   ...
      // },
    ];
    
    // Extracting the 'online' and 'max' values
    const playersInfo = responseData.map((data) => {
      const { online, max } = data.players;
      return { online, max };
    });
    
    console.log(playersInfo);
    

    Map function iterates over each element in the responseData array and extracts the online and max values from the players object of each element. It then creates a new array called playersInfo containing objects with the extracted online and max values for each data point.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search