Reputation:
I have a json where I have similar attributes like:
{
"audio_file1": "...",
"audio_file2": "...",
"audio_file3": "...",
"audio_file4": "...",
...
}
I'm trying to remove all attributes audio_fileX
. My first try was using a for/loop
in a function that receives the array, initial position and maximum number of file.
What is the most eficient way to remove attributes like audio_fileX
?
Upvotes: 0
Views: 41
Reputation: 387
From your question it's a bit tough to tell if you're working with JSON (as you say) or a JavaScript object.
For this answer, I'll assume it's JSON that you've imported one way or another and have converted it to a JavaScript object through JSON.parse()
.
So getting that out of the way, you're left with:
const obj = {
audio_file1 : "...",
audio_file2 : "...",
audio_file3 : "...",
audio_file4 : "...",
...
};
From here, you want to go through the object and find the keys that contain the string 'audio_file' and remove them from the object.
Below is a snippet demonstrated how this can be accomplished with ES6 methods:
const obj = {
audio_file1 : "...",
audio_file2 : "...",
audio_file3 : "...",
audio_file4 : "...",
};
for (let key in obj) {
if (key.startsWith('audio_file')) {
delete(obj[key]);
}
}
console.log(obj);
For a brief explanation of this, the code goes through each key of your object and checks if it starts with 'audio_file' and if so, it deletes it. You can see at the end the console logs an empty object as all of the current keys start with that string.
Upvotes: 0
Reputation: 21628
Reduce the properties to a new object, each iteration of the reduce either spreads the property into a new result if the property doesn't start with the string or it return the previous result without the property.
removeBetterPerformance does the same thing but mutates the previous result for better performance but sacrifices functional purity. This is unnecessary for a small number of properties.
let obj = {
audio_file1: "...",
audio_file2: "...",
audio_file3: "...",
audio_file4: "...",
other: "..."
};
const remove = (obj, str) =>
Object.getOwnPropertyNames(obj).reduce(
(result, property) => (property.startsWith(str) ? result : { ...result, [property]: obj[property] }),
{}
);
console.log(remove(obj, 'audio_file'));
const removeBetterPerformance = (obj, str) =>
Object.getOwnPropertyNames(obj).reduce((result, property) => {
if (!property.startsWith(str)) {
result[property] = obj[property];
}
return result;
}, {});
Upvotes: 0
Reputation: 33726
To avoid overhead using spread syntax ...
from other answers, I recommend you to use the function Object.assign
.
const obj = { "audio_file1": "...", "audio_file2": "...", "audio_file3": "...", "audio_file4": "...", "myown": "Ele"},
start = "audio_file",
result = Object.keys(obj).reduce((a, c) => c.startsWith(start) ? a : Object.assign(a, {[c]: obj[c]}), Object.create(null));
console.log(result);
Upvotes: 2