What would be the best approach using javascript? filter and map? or something else.
If you want to take a functional approach, just map
(copying the objects), you're not filtering.
If not, just forEach
modifying the existing objects:
Here's the map
version:
var originaldata = [{
"name": "john",
"content": "<div class='ExternalClass06EE5E42165840F48DFA193ACAD4F87A'>aa</div>"
},
{
"name": "mary",
"content": "<div class='ExternalClass3D5F8061F3DE49C4BC55A9CE0ADD6F9A'>asd</div>"
}];
var temp = document.createElement("div");
var modifieddata = originaldata.map(entry => {
temp.innerHTML = entry.content;
return {
name: entry.name,
content: temp.firstChild.firstChild.nodeValue
};
});
console.log(modifieddata);
...or using a Stage 3 proposal for object property spread that browser vendors are actively adding (Chrome has it, for instance), we can avoid having to know the names of the other properties:
// Note: I have the "Use BabelJS / ES2015" checkbox ticked
// so this will work even in browsers that don't
// have property spread yet.
const originaldata = [{
"name": "john",
"content": "<div class='ExternalClass06EE5E42165840F48DFA193ACAD4F87A'>aa</div>"
},
{
"name": "mary",
"content": "<div class='ExternalClass3D5F8061F3DE49C4BC55A9CE0ADD6F9A'>asd</div>"
}];
const temp = document.createElement("div");
const modifieddata = originaldata.map(entry => {
temp.innerHTML = entry.content;
return {
...entry, // <=== Property spread
content: temp.firstChild.firstChild.nodeValue
};
});
console.log(modifieddata);
Here's the forEach
version:
var originaldata = [{
"name": "john",
"content": "<div class='ExternalClass06EE5E42165840F48DFA193ACAD4F87A'>aa</div>"
},
{
"name": "mary",
"content": "<div class='ExternalClass3D5F8061F3DE49C4BC55A9CE0ADD6F9A'>asd</div>"
}];
var temp = document.createElement("div");
originaldata.forEach(entry => {
temp.innerHTML = entry.content;
entry.content = temp.firstChild.firstChild.nodeValue;
});
console.log(originaldata);
In a comment you've said:
If there is additional HTML tags within the DIV would this also be removed. Ideally I would like to keep all the content within the DIV even if its other tags. Is this also possible?
In that case, in all of the above, change
entry.content = temp.firstChild.firstChild.nodeValue;
to
entry.content = temp.firstChild.innerHTML;
Here's the forEach
with that change:
var originaldata = [{
"name": "john",
"content": "<div class='ExternalClass06EE5E42165840F48DFA193ACAD4F87A'>aa<span>stuff in a span</span><br></div>"
},
{
"name": "mary",
"content": "<div class='ExternalClass3D5F8061F3DE49C4BC55A9CE0ADD6F9A'>asd</div>"
}];
var temp = document.createElement("div");
originaldata.forEach(entry => {
temp.innerHTML = entry.content;
entry.content = temp.firstChild.innerHTML;
});
console.log(originaldata);