Follow @buddypia
Home AI Backend Frontend Infra
Follow @buddypia
DOC_MANIFEST
FILE: POST_3256.md
CAT: OTHERS
EST_READ: 2 min read
HASH: e4231b8

JSONのプロパティを再帰的にnullに初期化する関数

ネットで調べても見当たらなかったので作ってみました。

const json = JSON.parse('{"id":"vhUfi3t31goA","string":"root","number":1,"arrayString":["string1","string2"],"arrayNumber":[1,2],"object":{"childId":"boihF33gS3","childString":"child","childNumber":1,"childArrayString":["child_string1","child_string2"],"childArrayNumber":[1,2]}}');

SetNullRecursiveAllProperties(json);

function SetNullRecursiveAllProperties(obj) {
  for (var property in obj) {
    if (obj.hasOwnProperty(property) && typeof obj[property] === 'object') {
      SetNullRecursiveAllProperties(obj[property]);
    }
    else if (obj.hasOwnProperty(property)) {
      obj[property] = null;
    }
  }
}

console.log(json);
// > Object { id: null, string: null, number: null, arrayString: Array [null, null], arrayNumber: Array [null, null], object: Object { childId: null, childString: null, childNumber: null, childArrayString: Array [null, null], childArrayNumber: Array [null, null] } }
Buddypia
Buddypia
Software Engineer / AI Practitioner
Follow on 𝕏

AI駆動開発、MCP(Model Context Protocol)、コーディングエージェントの現場導入と実践ナレッジを発信しています。

// SHORTCUTS: ⌘K Quick Search / Command Line T Toggle Theme J Prev Post K Next Post