-3

How to fetch the length and individual values in javascript here is example data

examples:
       "numbers": "248001,248142",
        "numbers": "588801,248742,588869"

Actuall code
        {
            "_id" : ObjectId("579ce69f4be1811f797fbab2"),
            "city" : "",
            "sdescription" : "",
            "categories" : [
                    "5729f312d549cc3212c8393b"
            ],
            "numbers" : "4555855,421201",
            "createdAt" : ISODate("2016-07-30T17:40:47.022Z"),
            "month" : 7,
            "year" : 2016    
    }
here is my code and error

let num = numbers.split(',')
(node:5628) UnhandledPromiseRejectionWarning: TypeError: numbers.split is not a function

I have tried split to separate the values but some times it returns an error as number.split is not a function.

I want to return two things:

  1. length: in the first example length should be 2 and in the second example length should be 3.

2.values should get split

Schüler
  • 512
  • 4
  • 10
  • 25
  • 1
    Please show your code. See [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – p.s.w.g Mar 16 '19 at 17:09
  • 1
    How `"numbers": "248001,248142"` this is stored ? array ? string ? – Code Maniac Mar 16 '19 at 17:09
  • @CodeManiac Have updated please check. it is inside json object – Schüler Mar 16 '19 at 17:15
  • @p.s.w.g updated please check – Schüler Mar 16 '19 at 17:15
  • No. We need to see the *actual* code for how you are trying to parse this object. Where does `numbers` come from? The error indicates that it's not a string, and therefore the issue is probably due to how you're getting that variable. – p.s.w.g Mar 16 '19 at 17:27

2 Answers2

0

You need to call start from object name objectname.keyname

var obj = { "city": "", "sdescription": "", "categories": [ "5729f312d549cc3212c8393b" ], "numbers": "4555855,421201", "month": 7, "year": 2016 }
var res = obj.numbers.split(',').length;
console.log(res)
prasanth
  • 22,145
  • 4
  • 29
  • 53
  • but some times it returns `(node:16568) UnhandledPromiseRejectionWarning: TypeError: numbers.split is not a function` – Schüler Mar 16 '19 at 17:21
0

You can loop through your object and then for each element access numbers property and then split and find length

let json = [{"numbers": "248001,248142"},{"numbers": "588801,248742,588869"},{"numbers":[]}]

json.forEach(({numbers})=>{
  console.log(typeof numbers === 'string' ? numbers.split(',').length : 'Not a string')
})
Code Maniac
  • 37,143
  • 5
  • 39
  • 60