在 object javascript 的数组中引用 object

Reference object in an array in an object javascript

我希望这个标题有意义...我对使用 Javascript 做任何事情都很陌生,我已经搜索了一段时间了。

我正在使用 Node-RED 接收包含 JSON 的 HTTP POST。我在 msg.req.body 中发布了以下数据,并想在 targets:

中提取 objects
    {
    "policy_url": "https://alerts.newrelic.com/accounts/xxxxx/policies/7477",
    "condition_id": 429539,
    "condition_name": "Error rate",
    "account_id": 773524,
    "event_type": "INCIDENT",
    "runbook_url": null,
    "severity": "CRITICAL",
    "incident_id": 50,
    "version": "1.0",
    "account_name": "Inc",
    "timestamp": 1436451988232,
    "details": "Error rate > 5% for at least 3 minutes",
    "incident_acknowledge_url": "https://alerts.newrelic.com/accounts/xxxxxx/incidents/50/acknowledge",
    "owner": "Jared Seaton",
    "policy_name": "Default Policy",
    "incident_url": "https://alerts.newrelic.com/accounts/xxxxxx/incidents/50",
    "current_state": "acknowledged",
    "targets": [{
        "id": "6002060",
        "name": "PHP Application",
        "link": "https://rpm.newrelic.com/accounts/xxxxxx/applications/6002060?tw[start]=1436450194&tw[end]=1436451994",
        "labels": {

        },
        "product": "APM",
        "type": "Application"
    }]
}

我想格式化一个字符串以通过 TCP 发送以将事件插入到我们的事件管理系统中。所以我尝试了以下方法:

msg.payload = msg.req.body.targets[0] + "|" + msg.req.body.severity + "|" + msg.req.body.current_state + "|" + msg.req.body.details + "|" + msg.req.body.condition_name + "\n\n";
return(msg);

这导致消息:

[object Object]|CRITICAL|acknowledged|Error rate > 5% for at least 3 minutes|Error rate 

我尝试了一些不同的方法,但要么得到空值 return,要么得到 [object Object]。感觉我很接近...

有人可以帮忙吗?

提前致谢。

target[0] 是一个对象,这就是您看到 [object Object] 的原因。

您应该改为 msg.req.body.targets[0].name 来访问该对象的 属性。

结果消息看起来像这样

PHP Application|CRITICAL|acknowledged|Error rate > 5% for at least 3 minutes|Error rate 

你想要JSON.stringify()

msg.payload = JSON.stringify(msg.req.body.targets[0]) + "|" + msg.req.body.severity + "|" + msg.req.body.current_state + "|" + msg.req.body.details + "|" + msg.req.body.condition_name + "\n\n";
return(msg);

这会将存储在目标数组第一个槽中的对象转换为其字符串表示形式。