I have an array of objects
const test = [
{col1: "na", col2: "string", col3: "na"},
{col1: 100, col2: "String", col3: "2019-01-01"},
{col1: 203, col2: "na", col3: "2019-01-01"}
]
And I want to use vanilla JS to create a function naOmit that will replace the "na" strings with undefined:
console.log(naOmit(test))
[
{col1: undefined, col2: "string", col3: undefined},
{col1: 100, col2: "String", col3: "2019-01-01"},
{col1: 203, col2: undefined, col3: "2019-01-01"}
]
Already Tried: I've tried playing with a function that works for nested arrays, but I'm not sure how to apply this to an array of objects (or if this is even the right route)
rows = [
["na", "string", "na"],
[100, "String", "2019-01-01"],
[203, "na", "2019-01-01"]
]
rows.map(function(x){ return x.map(function(y){ y === "na"? undefined: y})})
Any help appreciated!
You could iterate the objects and replace if wanted string is found.
function replace(object, search, replace) {
function iter(object) {
Object.keys(object).forEach(k => {
if (object[k] && typeof object[k] === 'object') return iter(object[k]);
if (object[k] === search) object[k] = replace;
});
}
iter(object);
}
const test = [{ col1: "na", col2: "string", col3: "na" }, { col1: 100, col2: "String", col3: "2019-01-01" }, { col1: 203, col2: "na", col3: "2019-01-01" }]
replace(test, 'na', undefined);
console.log(test);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With