[英]Remove item by value from array with different keys
我正在尝试创建一个从我的 JSON 文件中删除一个单词的函数。
功能:
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!');
});
});
}
原始 JSON:
{"en":["moon","crazy"],"pt":["macaco", "macarrão"],"es":["hola"]}
通过调用 removeword('pt', 'macaco'),这是我的期望:
{"en":["moon","crazy"],"pt":["macarrão"],"es":["hola"]}
您可以为给定的键在您的items
数组上调用.filter()
,您可以通过。 对于数组中不是您的值的任何元素,您可以通过返回true
( v !== value
) 来保留它,否则,您可以删除它(通过返回 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"]}
如果您不想修改您的items
数组(而是返回一个新的修改过的items
数组),您可以使用Object.fromEntries()
从[key, value]
对数组创建一个新对象,您可以在其中过滤value
数组,如果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"]}
请参阅Object.fromEntries()
浏览器兼容性
上面不可变方法的浏览器兼容版本会使用.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"]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.