0

There is JSON of this format

{
  "key1": {
    "data1": null
  },
  "key2": {
    "data2": null
  },
  "key3": {
    "data3": "123",
    "data4": "456"
  },
  "key4": {
    "data5": "789"
  },
  "key5": {
    "data6": null
  }
}

I'm trying to remove all nulls:

const removeNulls = (o : string): string => {
    for (let key = 0; key < o.length; key++) {
        for (let data = 0; data < o[key].length; data++) {
            if (o[key][data] === null) {
                delete o[key][data];
            }
        }
    }
    return o;
}

but I receive Index signature in type 'String' only permits reading.. What am I doing wrong and how to fix it?

  • `o : string` is wrong. If you really have JSON, then it is a *string* but you cannot traverse it like an object or modify it. It needs to be deserialised into an actual object. If what you have is an actual object, and thus *not* JSON, then the typing is wrong. Relevant: [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/q/2904131) – VLAZ Oct 13 '22 at 16:57
  • You need to first [parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) the JSON (deserialize it) in order to work with its parsed representation (an object in this case). – jsejcksn Oct 13 '22 at 16:58
  • In addition to all that, if you have an object, then the way you traverse it is wrong. Traversing plain objects cannot be done with a plain indexed for-loop. You need to use other methods. `for..in` or `Object.keys()` or `Object.entries()` and more. – VLAZ Oct 13 '22 at 17:00
  • thanks @VLAZ. I updated the code in my answer. – Мария Гутовская Oct 16 '22 at 10:24

1 Answers1

0

Finally this works:

const removeNulls = (o: Object): Object => {
    for (let k in 0) {
        let kKey = k as keyof typeof o
        for (let d in o[kKey]) {
            let dKey = d as keyof typeof o;
            if (o[kKey][dKey] == null) {
                delete o[kKey][dKey];
            }
        }
        if (Object.entries(o[kKey]).length == 0) {
            delete o[kKey];
        }
    }
    return o;
}