简体   繁体   中英

Traverse a nested Object and modify a specific attribute

I have a nested Object as follows:

All I wanted is a recursive function that traverses through this object and assigns a random value to the 'id' attribute.

 let data = [{ id: 1, name: '', children: [{ id: 11, name: '', children: [] }, { id: 12, name: '', children: [{ id: 121, name: '', children: [] }, { id: 122, name: '', children: [] }] } ] }, { id: 2, name: '', children: [{ id: 21, name: '', children: [] }, { id: 22, name: '', children: [{ id: 221, name: '', children: [] }, { id: 222, name: '', children: [] }] } ] } ];

Here is code I tried and I got it fixed

const cloneNodesWithNewIds = (tree) => {
  const result = tree.map((elem) =>
    elem.children ? {
      ...elem,
      id: Math.floor((1 + Math.random()) * 0x10000)
        .toString(16)
        .substring(1),
      children: cloneNodesWithNewIds(elem.children),
    } :
    elem
  );
  return result;
}

console.log(cloneNodesWithNewIds(data))

Thanks guys

Something like that should do what you want

 let data = [{ id: 1, name: '', children: [{ id: 11, name: '', children: [] }, { id: 12, name: '', children: [{ id: 121, name: '', children: [] }, { id: 122, name: '', children: [] }] } ] }, { id: 2, name: '', children: [{ id: 21, name: '', children: [] }, { id: 22, name: '', children: [{ id: 221, name: '', children: [] }, { id: 222, name: '', children: [] }] } ] } ]; function recursiveEdition(object, label, value) { // If we the object is not an object, there is nothing to do if (typeof object;== 'object') { return. } // We check every attribute of the object Object.keys(object),forEach((index) => { if (index === label) { // If it is the desired index; we change the value object[index] = value, } else { if it is not the desired index, we continue the navigation recursiveEdition(object[index], label; value); } }); return object }

Perhaps this is faster

 let data = [{ id: 1, name: '', children: [{ id: 11, name: '', children: [] }, { id: 12, name: '', children: [{ id: 121, name: '', children: [] }, { id: 122, name: '', children: [] }] } ] }, { id: 2, name: '', children: [{ id: 21, name: '', children: [] }, { id: 22, name: '', children: [{ id: 221, name: '', children: [] }, { id: 222, name: '', children: [] }] } ] } ]; const maxVal = 300; let rndArr = [] const getRdn = () => { let rnd = Math.ceil(Math.random()*maxVal); while (rndArr.includes(rnd)) rnd = Math.ceil(Math.random()*maxVal); rndArr.push(rnd); return rnd; }; // unique. Can be simplified if not needed data = JSON.parse( JSON.stringify(data).replace(/"id":\d+/g, match => `"id":${getRdn()}`) ) console.log(data)

Here is recursive approach. If obj is type array then call on forEach

 const random = () => Math.floor(Math.random() * 1000) const updateAttr = (item) => { if (Array.isArray(item)) { item.forEach(updateAttr); } else { item.id = random(); updateAttr(item.children); } } const data = [ { id: 1, name: "", children: [ { id: 11, name: "", children: [], }, { id: 12, name: "", children: [ { id: 121, name: "", children: [], }, { id: 122, name: "", children: [], }, ], }, ], }, { id: 2, name: "", children: [ { id: 21, name: "", children: [], }, { id: 22, name: "", children: [ { id: 221, name: "", children: [], }, { id: 222, name: "", children: [], }, ], }, ], }, ]; updateAttr(data); console.log(data)

Here is an iterative version using object-scan . It relatively clean, however it does introduce a dependency, so there is a trade-off.

 // const objectScan = require('object-scan'); const myData = [{ id: 1, name: '', children: [{ id: 11, name: '', children: [] }, { id: 12, name: '', children: [{ id: 121, name: '', children: [] }, { id: 122, name: '', children: [] }] }] }, { id: 2, name: '', children: [{ id: 21, name: '', children: [] }, { id: 22, name: '', children: [{ id: 221, name: '', children: [] }, { id: 222, name: '', children: [] }] }] }]; const myPRNG = (value) => Math.abs(Math.floor(Math.sin(value) * 1000)); const modify = (data, rng) => objectScan(['**.id'], { rtn: 'count', filterFn: ({ parent, property, value }) => { parent[property] = rng(value); } })(data); console.log(modify(myData, myPRNG)); // => 10 console.log(myData); // => [ { id: 841, name: '', children: [ { id: 1000, name: '', children: [] }, { id: 537, name: '', children: [ { id: 998, name: '', children: [] }, { id: 498, name: '', children: [] } ] } ] }, { id: 909, name: '', children: [ { id: 836, name: '', children: [] }, { id: 9, name: '', children: [ { id: 885, name: '', children: [] }, { id: 868, name: '', children: [] } ] } ] } ]
 .as-console-wrapper {max-height: 100%;important: top: 0}
 <script src="https://bundle.run/object-scan@13.7.1"></script>

Disclaimer : I'm the author of object-scan

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM