2

Hi I am wondering how I can check a length of a response which is not an array of objects? Can't really shot an example because I don't know how exactly it works in backed I mean I'm looping through an object in a game (which is a battle) and it prints all enemies. But i am getting response with separated objects, not an array of objects. So my response looks like:

{name: "Mike", lvl: 169, team: 1, …}
{name: "Mike2", lvl: 120, team: 1, …}

But not an array of these objects. So I don't really know how I can check what length it is, if it's not an array of objects...

Bahman Parsa Manesh
  • 2,314
  • 3
  • 16
  • 32
Suttero
  • 91
  • 7

3 Answers3

0
let json1 = {name: "Mike", lvl: 169, team: 1};
let json2 = {name: "Mike2", lvl: 120, team: 1};
console.log (Object.keys(json1).length);
console.log (Object.keys(json2).length);

Answer: 3

Ankit
  • 562
  • 5
  • 12
0

Hei,

You can check the number of keys your object has:

const obj = {
  a: 'cool stuff',
  b: 42,
  c: false
};

const count = Object.keys(obj).length

console.log(count);

The function has full support and you can read more about it here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Cheers!

syntax-punk
  • 3,736
  • 3
  • 25
  • 33
  • As i mention i am getting response as a separated objects. And i want to check how much of them i got. Not a length of an object. – Suttero Aug 02 '18 at 07:17
  • Ohh, I got it. Then you're probably getting them as a 'newline' separated string, am I right? – syntax-punk Aug 02 '18 at 07:21
  • Yes, every object is printed in a new line. I've tried to push it to an array. which is outside the loop, and the print the array inside a loop. But it prints this array 1 by 1. Similar to what im getting as a response but now its an array with 1 object inside instead of 1 whole array. – Suttero Aug 02 '18 at 07:24
  • @Suttero what's wrong with the loop? does it not behave like this? https://codepen.io/hibijvs/pen/pZVoMp – Community Aug 02 '18 at 07:49
0

Looks like your wanting to split on lines,..

var a = `{name: "Mike", lvl: 169, team: 1, …}
{name: "Mike2", lvl: 120, team: 1, …}`;

console.log("count = " + a.split(/\r?\n/g).length);

//if each line was valid JSON, could even go one better
//and make into an array

var b = `{"name": "Mike", "lvl": 169, "team": 1}
{"name": "Mike2", "lvl": 120, "team": 1}`

b = b.split(/\r?\n/g).map(m => JSON.parse(m));

console.log(b);
Keith
  • 22,005
  • 2
  • 27
  • 44