简体   繁体   中英

Updating unknown Immutable.js Map structure

My task is to update deep nested values for which I don't know the path because the data is dynamic.

Example:

const errors = Immutable.fromJS({
  clients: [
    {
      users: {
        names: ["Joseph", "John"],
        items: ["Passport", "ID"],
      },
    },
  ],
  items: {
    data: {
      codes: ["543", "765", "549"],
    },
  },
});

Desired output:

const errors = Immutable.fromJS({
  clients: [
    {
      users: {
        names: "Joseph,John",
        items: "Passport,ID",
      },
    },
  ],
  items: {
    data: {
      codes: "543,765,549",
    },
  },
});

In this case, I need to concatenate all the strings inside the nested arrays (lists). I can join the nested array, but I need to somehow get to it first. I was thinking about getting the Map nested structure, but haven't found a method for it (only for keys at the same level). Can this be done in Immutable.js? If so, how?

You can simply use recursivity to parse and update the lists containing strings/numbers:

 let errors = Immutable.fromJS({ clients: [ { users: { names: ["Joseph", "John"], items: ["Passport", "ID"], }, }, ], items: { data: { codes: ["543", "765", "549"], }, }, }); const update = (object) => { if (typeof object.map === 'function') { return object.map((value) => { if (Immutable.List.isList(value) && value.every((val) => ['string', 'number'].includes(typeof val)) ) { return value.join(); } return update(value); }); } return object; } errors = update(errors); console.log(errors);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.min.js"></script>

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