skip to Main Content

I have a dynamic array which can have n number of sections/fields as below.

[
    {
        "id": "section-1",
        "fields": [{
                "id": "field1",
                "value": "A1"
            }, {
                "id": "field2",
                "value": null
            }
        ]
    }, {
        "id": "section-2",
        "fields": [{
                "id": "field3",
                "value": null
            }, {
                "id": "field4",
                "value": null
            }
        ]
    }, {
        "id": "section-3",
        "fields": [{
                "id": "field5",
                "value": "A5"
            }
        ]
    }
]

Can I use ES6 to update any null values to empty string in this array. So the output would be the same exact structure replacing any "value": null with "value": ""

2

Answers


  1. Nested forEach() calls:

    const data = [{
      "id": "section-1",
      "fields": [{
        "id": "field1",
        "value": "A1"
      }, {
        "id": "field2",
        "value": null
      }]
    }, {
      "id": "section-2",
      "fields": [{
        "id": "field3",
        "value": null
      }, {
        "id": "field4",
        "value": null
      }]
    }, {
      "id": "section-3",
      "fields": [{
        "id": "field5",
        "value": "A5"
      }]
    }];
    
    data.forEach(section => section.fields.forEach(field => {
      if (field.value === null) {
        field.value = "";
      }
    }));
    
    console.log(data);
    Login or Signup to reply.
  2. You can use a pretty simple neat trick using JSON.parse and JSON.stringify using reviver parameter as:

    It will replace null with "" doesn’t matter how nested object it is.

    JSON.parse(JSON.stringify(obj), (key, value) => value === null ? "": value)
    
    const obj = [
        {
            "id": "section-1",
            "fields": [{
                "id": "field1",
                "value": "A1"
            }, {
                "id": "field2",
                "value": null
            }
            ]
        }, {
            "id": "section-2",
            "fields": [{
                "id": "field3",
                "value": null
            }, {
                "id": "field4",
                "value": null
            }
            ]
        }, {
            "id": "section-3",
            "fields": [{
                "id": "field5",
                "value": "A5"
            }
            ]
        }
    ]
    
    const result = JSON.parse(JSON.stringify(obj), (key, value) => value === null ? "": value)
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search