[英]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.