0

I want to stringify my json but I want to exclude empty nested arrays of objects.

My json looks likt this:

{
  "Fe": {
    "Fh": {
        "a" : 1,
        "b" : "foo"
      },
      "Fb": {
          "Dbs": [
                  {
                    "Nl": "1",
                    "Dt": "red",
                  }
                 ],
          "Dr": [
                  {
                  }
               ]
        }
}

I want to to ignore "Dr" because it is empty.

How can I do it in typescript/Javascript?

Here it the code that I have tried:

const str = JSON.stringify(this.json, replacer);

replacer(key, value) {
		if (value === null || value === {})
			return undefined;
		else
			return value;
	};

Thanks

3
  • 3
    Be sure to post the code where you tried to accomplish your goal. Commented Oct 16, 2018 at 19:25
  • Yes, please post you code.... also take a look here Commented Oct 16, 2018 at 19:32
  • Have you looked at this? stackoverflow.com/questions/38521648/… Commented Oct 16, 2018 at 19:32

2 Answers 2

2

I came across a similar issue, the accepted answer gave me a great starting point, but I needed something a bit more robust to work with a dynamic structure with deeply nested keys.

Here's what I came up with, thought it might be helpful to share for anyone else who comes across this question:

function isEmpty(value) {
  if (value === null || value === undefined) {
    return true;
  }

  if (Array.isArray(value)) {
    return value.every(isEmpty);
  }
  else if (typeof (value) === 'object') {
    return Object.values(value).every(isEmpty);
  }

  return false;
}

function replacer(key, value) {
  return isEmpty(value)
    ? undefined
    : value;
}

function getPrettyJSON(obj: any) {
  return JSON.stringify(obj, replacer, 2);
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could use a replacer and check if the value is an array and if the items are empty objects.

var object = { Fe: { Fh: { a: 1, b: "foo" }, Fb: { Dbs: [{ Nl: "1", Dt: "red" }], Dr: [{}] } } }, 
    json = JSON.stringify(
        object,
        (k, v) => Array.isArray(v) && v.every(o => JSON.stringify(o) === '{}')
            ? undefined
            : v
    );

console.log(json);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.