I'm trying to create a function that removes a word from my JSON file.
Function:
function removeword(lang,word) {
var farr = [];
var count = 0;
fs.readFile('./dictionary.json', 'utf8', (err, jsonString) => {
var items = JSON.parse(jsonString);
for (var i = 0; i < items.length; i++) {
console.log(items[lang][i]);
if (word === items[lang][i]) {
items[lang].splice(i, 1);
}
}
console.log(items);
fs.writeFile("./dictionary.json", JSON.stringify(items), function(err){
if (err) throw err;
console.log('Done!');
});
});
}
Original JSON:
{"en":["moon","crazy"],"pt":["macaco", "macarrão"],"es":["hola"]}
by calling removeword('pt', 'macaco'), here's what I expect:
{"en":["moon","crazy"],"pt":["macarrão"],"es":["hola"]}
You can call .filter()
on your items
array for the given key, you pass. For any element in your array which isn't your value, you can keep it by returning true
( v !== value
), otherwise, you can remove it (by returning false):
const items = {"en":["moon","crazy"],"pt":["macaco", "macarrão"],"es":["hola"]}; function removeword(obj, key, value) { obj[key] = obj[key].filter(v => v !== value); } removeword(items, 'pt', 'macaco'); console.log(items); // {"en":["moon","crazy"],"pt":["macarrão"],"es":["hola"]}
If you don't want to modify your items
array (and instead return a new modified items
array) you can use Object.fromEntries()
to create a new object from the [key, value]
pair arrays, where you can filter the value
array if the key
matches your passed in key:
const items = {"en":["moon","crazy"],"pt":["macaco", "macarrão"],"es":["hola"]}; const removeword = (obj, key, value) => Object.fromEntries( Object.entries(obj).map(([k, arr]) => k === key ? [k, arr.filter(v => v !== value)] : [k, arr]) ); const result = removeword(items, 'pt', 'macaco'); console.log(result); // {"en":["moon","crazy"],"pt":["macarrão"],"es":["hola"]}
See browser compatibility for Object.fromEntries()
A slightly more browser compatible version of the immutable method above would be to use .reduce()
:
const items = {"en":["moon","crazy"],"pt":["macaco", "macarrão"],"es":["hola"]}; const removeword = (obj, key, value) => Object.keys(obj).reduce((o, k) => ({...o, [k]: k === key ? obj[k].filter(v => v !== value) : obj[k]}), {}) const result = removeword(items, 'pt', 'macaco'); console.log(result); // {"en":["moon","crazy"],"pt":["macarrão"],"es":["hola"]}
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.