2

I want to parse this JSON array and print the salary so this what I have tried so far there is nothing logged in the Console

if (data.action == 'SendArray') {
  let invites = data.invites
  const obj = JSON.parse(invites)
  const myJSON = JSON.stringify(obj);
  console.log(myJSON.salary)
}

JSON:

{"factioname":"sp-force","inviter":"MohammedZr","salary":5000},
{"factioname":"air-force", "inviter":"Admin","salary":8000}
4
  • 1
    What are you trying to achieve? What is JSON Array? Which salary? What is 2 line? Commented Jul 29, 2022 at 0:31
  • 1
    Also, on an important technical note, there is no such thing as a "JSON Object" (short of the actual JSON object): either something is JSON, i.e. a string representation of (part of) a JS object and then it is a string and things like myJSON.salary make no sense (strings don't have a .salary property), or it's literally just a normal, plain, "boring" object. And on a JS note: never use ==, always use === unless your conditional only works because type coercion. Commented Jul 29, 2022 at 0:48
  • You can not use dot notation on json files. It works on objects. You Should log obj.salary. Commented Jul 29, 2022 at 0:54
  • trivial answer: json = [{"factioname":"sp-force","inviter":"MohammedZr","salary":5000}, {"factioname":"air-force", "inviter":"Admin","salary":8000}] for ({salary} of json) console.log(salary) Commented Jul 29, 2022 at 1:11

2 Answers 2

1

This const myJSON = JSON.stringify(obj) turns your object back into a string, which you don't want.

I've done some setup to get your data matching your code but the two things you should note are:

  1. Iterating through the array of invites using for .. of (you could use forEach instead) and
  2. Using deconstruction to pull out the salary

data = { action: 'SendArray'
       , invites: '[{"factioname":"sp-force","inviter":"MohammedZr","salary":5000},{"factioname":"air-force", "inviter":"Admin","salary":8000}]'
       }
       
if (data.action == 'SendArray') {
  let invites = data.invites
  const obj = JSON.parse(invites)
  for ({salary} of JSON.parse(invites))
    console.log(salary)}

Sign up to request clarification or add additional context in comments.

Comments

0

myJSON is an array of objects. To log in console need to get each object. we can use forEach to get each object and then can console log the salary key.

let myJSON =[
  {"factioname":"sp-force","inviter":"MohammedZr","salary":5000},
  {"factioname":"air-force", "inviter":"Admin","salary":8000}];
  
myJSON.forEach(obj=> {
  console.log(obj.salary);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.