1

I have an array,

var test = [{
        id: 0,
        test_id: "Password test",
        pass: 1,
        fail: 5,
        time: 0.03,
        pass_fail: 20,
        comments : [
            {comment : "a comment", commentuser : "user" },
        ]
    };
]

within I want to get the value of comment and commentuser in the object comments. I tried as follows,

JSON.stingify(test.comments) // output : "{"comment":"a comment","commentuser":"user"}"

Is there a way to just get the value ? wanted output : "a comment,user"

Cheers

2
  • 1
    If it is an array with only one element you can just get it as follows: var comment = test[0].comments[0].comment; var commentuser = test[0].comments[0].commentuser; Commented Nov 25, 2019 at 13:15
  • var output = ${test[0].comments[0].comment},${test[0].comments[0].commentuser} backticks at the start and end. Commented Nov 25, 2019 at 13:21

1 Answer 1

1

Join the Object.values of test[0].comments[0] :

var test = [{
  id: 0,
  test_id: "Password test",
  pass: 1,
  fail: 5,
  time: 0.03,
  pass_fail: 20,
  comments: [{
    comment: "a comment",
    commentuser: "user"
  }]
}]

var result = Object.values(test[0].comments[0]).join(',');

console.log(result);

Or deep destructure the object you want and join the Object.values :

var test = [{
  id: 0,
  test_id: "Password test",
  pass: 1,
  fail: 5,
  time: 0.03,
  pass_fail: 20,
  comments: [{
    comment: "a comment",
    commentuser: "user"
  }]
}]

var [{
  comments: [obj]
}] = test;

var result = Object.values(obj).join(',');

console.log(result);

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

Comments

Your Answer

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