简体   繁体   中英

Node js , replacing occurrences in a nested data structure

Basically I want to replace # occurrences in a string from an object. As you can see it replace occurences in templateName, description, comments and Name but I can't replace sections header and sections questions, how will I improve my loop to apply replaceOccurrences in sections.header and sections questions array of objects? . sections headers are array of objects I also want to include that. Any idea? thank you.

Code

const replaceOccurrences = (originalString) => (typeof originalString === 'string' ? originalString.replace(/#/g, '#') : originalString);

const generateTemplate = async (data) => {

  for (const [k, v] of Object.entries(data)) { data[k] = replaceOccurrences(v); }

  return template(data);
};

Data

data :  {
  Name: 'Rajesh',
  sections: [
    {
      questions: [Array]
    }
  ],
  templateName: 'TEMPLAT#E',
  description: 'Tes#t',
  comments: "adasdada'dfgdfgdfg 'gfddf#gdfgdf #num;## ##fsdfds gdfgdfgfd##"
}

You can stringify the object, make your replacements, then return it to object form:

let a = JSON.stringify(data).replace(/#/g, '#');
let b = JSON.parse(a);

Name: "Rajesh"
comments: "adasdada'dfgdfgdfg 'gfddf#gdfgdf #num;## ##fsdfds gdfgdfgfd##"
description: "Tes#t"
sections: Array(1)
0: {header: "Testing sec#tion", questions: Array(1)}
length: 1
__proto__: Array(0)
templateName: "TECHNICAL TEMPLAT#E"

James's answer will work if your obj is serializable, otherwise you'll need a recursive function

const removePoundSign = cur => {
  if (typeof cur === 'string') {
    return cur.replace(/#/g, '#');
  }

  if (cur == null || typeof cur !== 'object') return cur;

  if (Array.isArray(cur)) {
    return cur.map(el => removePoundSign(el));
  }

  const newObj = {};
  for (const key in cur) {
    newObj[key] = removePoundSign(cur[key]);
  }
  return newObj;
};

also, theres no need for the function to be async in your code!

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