JTouchLogic
JTouchLogic

Reputation: 57

Get only values of dynamic JSON in comma separated string in Typescript

I have this dynamic JSON -

    {
    "SMSPhone": [
        "SMS Phone Number is not valid"
    ],
    "VoicePhone": [
        "Voice Phone Number is not valid"
    ]
}

I need only values as comma separated string. Also, its dynamic so, i do not know the key names.

Desired result - SMS Phone Number is not valid,Voice Phone Number is not valid

Code i tried -

let res=JSON.parse(Jsondata);
   res.forEach(element => {
    console.log(element)
    //logic
  });

I am getting following error enter image description here

Upvotes: 0

Views: 526

Answers (2)

Damien
Damien

Reputation: 1600

I don't know what you want to achieve here. But you can't use forEach on an object. forEach is used to loop through data in an array. In your case, I would use object.entries() as shown below to achieve my goal.

const data = {
    "SMSPhone": [
        "SMS Phone Number is not valid"
    ],
    "VoicePhone": [
        "Voice Phone Number is not valid"
    ]
};


for (const [key, value] of Object.entries(data)) {
  console.log(`${key}: ${value}`);
}

Upvotes: 1

Patrick Smith
Patrick Smith

Reputation: 16

res is an object, so you can't use forEach. If you want to iterate over an object's values, you need to do something like:

for (const [key, value] of Object.entries(Jsondata)) {
  console.log(value);
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

Upvotes: 0

Related Questions