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

Legionar
7,5993 gold badges45 silver badges71 bronze badges
asked Nov 25, 2019 at 13:12
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);

answered Nov 25, 2019 at 13:18
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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