Remove fields from JSON Object

Asked by At

Hi can somebody help removing element from nested json array like this

{
"_id": "ProductionData1",
"_rev": "1-b4a160f5e13fab074d2fcc359e820d3f",
"topic": "",
"payload": {
"plant Operating Time": "600",
"plant stop": "10"
}
}

Lets say I want to remove the object "_id": "ProductionData1" "_rev": "1-b4a160f5e13fab074d2fcc359e820d3f" "topic": "", that should leave me with the following:

{
"payload": {
"plant Operating Time": "600",
 "plant stop": "10"
}
}

3 Answers

-1
Community On

If you are using Angular or Node

In Node or Angular to handle the response and use only particular variables from the object than try this.

let json ={
"_id": "ProductionData1",
"_rev": "1-b4a160f5e13fab074d2fcc359e820d3f",
"topic": "",
"payload": {
"plant Operating Time": "600",
"plant stop": "0"
}

Syntax to delete the element is angular is

    delete this.json['_rev']
    delete this.json['_id']
    delete this.json['topic']

The result after deleting this element you will get

{
"payload": {
"plant Operating Time": "600",
 "plant stop": "10"
}

Example DEMO

0
hardillb On

The change node will allow you to remove key value pairs from a the msg object.

enter image description here

From the info sidebar:

Set, change, delete or move properties of a message, flow context or global context.

The node can specify multiple rules that will be applied in turn.

The available operations are:

  • Set - set a property. The value can be a variety of different types, or can be taken from an existing message or context property.
  • Change - search & replace parts of the property. If regular expressions are enabled, the replace with property can include capture groups, for example $1. Replace will only change the type if there is a complete match.
  • Delete - delete a property.
  • Move - move or rename a property.
0
BornaS On

Try running your JSON through this function:

const jsonToTrim = {
   "_id": "ProductionData1",
   "_rev": "1-b4a160f5e13fab074d2fcc359e820d3f",
   "topic": "",
   "payload": {
      "plant Operating Time": "600",
      "plant stop": "0"
   }
};

function trimJSON(json, propsToRemove) {
    propsToRemove.forEach((propName) => {
      delete json[propName];
    });
}
// call the function 
trimJSON(jsonToTrim, ['_id', '_rev', 'topic']);
//inspect result
console.log(jsonToTrim);

This is the part that actually removes a property from your object: delete json[propName]; You can read more about delete here.

As far as the json[propName] is concerned it's an alternative way to writing json.propName and it allows us to have props names coming in dynamically (from an array).