skip to Main Content

When trying to filter location data using comma but I get the error [object Object],[object Object],[object Object Object],[object Object] Data json:

{
  "command": "lok",
  "params": {
    "action": "test",
  },
  "response": {
    "skc": "D400",
    "location": [
      {
        "city": "Lond.",
        "location": "1m23"
      },
      {
        "city": "Lond.",
        "location": "2df65"
      },
      {
        "city": "Lond.",
        "location": "3sk56"
      }
    ]
  }
}

The js code looks like this:

var lk = data.response.location;
console.log(lk);
var ghlok = lk.filter(function (item) {
        return item.location;
      }).join(",");
      console.log(ghlok);

console.log(lk); gives location in {"city": "Lond.", "location": "1m23"}...

console.log(ghlok); outputs [object Object Object],[object Object],...

I added var par = JSON.parse(lk); but I get the error

Unexpected token ‘o’, "[object Object Object"…. is not valid JSON

2

Answers


  1. var lk = data.response.location;
    console.log(lk);
    
    var ghlok = lk.map(function (item) {
      return item.location;
    }).join(",");
    
    console.log(ghlok);
    
    Login or Signup to reply.
  2. If you need to filter the array lk to include only elements that have a location, you can use lk.filter(i => i.location). To use the .join() method, you need a string array. To convert your location object to a string, you can use JSON.stringify() as shown below before applying join():

    var ghlok = lk.filter(i => i.location)
                  .map(i => JSON.stringify(i))
                  .join(',')
    

    it will output:

    {"city":"Lond.","location":"1m23"},{"city":"Lond.","location":"2df65"},{"city":"Lond.","location":"3sk56"}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search