首页 > 解决方案 > 在 JavaScript 数组中显示对象

问题描述

我有一个数组,

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

在我想在对象comments中获取commentcommentuser的值。我尝试如下,

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

有没有办法获得价值?想要的输出:“评论,用户

干杯

标签: javascriptarrays

解决方案


加入:Object.values_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);

或深度解构您想要的对象并加入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);


推荐阅读