简体   繁体   中英

Reference object in an array in an object javascript

I hope that title makes sense... I'm very new to doing anything with Javascript, and I've been searching for a while now.

I'm using Node-RED to receive an HTTP POST containing JSON. I have the following data being posted in msg.req.body, and want to pull out objects inside of targets :

    {
    "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"
    }]
}

I want to format a string to send via TCP to insert an event into our event management system. So I tried the following:

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);

This results in a message of:

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

I've tried a few different things, but I either get a null return, or the [object Object]. It feels like I'm close...

Can anyone assist?

Thanks in advance.

target[0] is an object and that is why you see [object Object].

You should instead do msg.req.body.targets[0].name to access the property of that object.

The result message would look something like this

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

You want 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);

This will turn the object that is stored in the first slot in the target array into it's string representation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM