如果pair的值是“Bridgeport”,我必须从地图中删除一些键值对:
let map = {
"country":"US",
"state": "CT",
"town": "Bridgeport"
}
并获得:
alteredMap = {
"country":"US",
"state": "CT",
}
'_.remove()'似乎不起作用,因为它只适用于数组。假设我们不知道地图的键,如果我们想要删除等于Bridgeport
的值,我们如何才能获得changedMap?
我在尝试:
_.reduce(map, (value,key)=>{
return value=='Bridgeport'
})
答案 0 :(得分:2)
如果对的值是,我必须从地图中删除一些键值对 “Bridgeport的”
vanilla js解决方案可能
Bridgeport
delete
从map
即
var valueToFind = "Bridgeport";
Object.keys(map)
.filter( s => map[s] == valueToFind ) //find keys with valueToFind
.forEach( s => delete map[s] ); //delete those keys
<强>演示强>
let map = {
"country":"US",
"state": "CT",
"town": "Bridgeport"
};
var valueToFind = "Bridgeport";
Object.keys(map)
.filter( s => map[s] == valueToFind )
.forEach( s => delete map[s] );
console.log(map);
答案 1 :(得分:2)
您可以使用omitBy
方法,该方法使用两个(value, key)
参数进行回调并返回一个新对象。您可以使用pickBy
方法执行相同操作,只需反转条件
_.pickBy(map, e => e != 'Bridgeport')
let map = {"country": "US","state": "CT","town": "Bridgeport"}
const result = _.omitBy(map, e => e == 'Bridgeport')
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>
答案 2 :(得分:0)
您可以使用Object.keys
遍历对象,然后使用Array.reduce
方法过滤掉所需的值。
let map = {
"country":"US",
"state": "CT",
"town": "Bridgeport"
};
var updatedMap = Object.keys(map).reduce((acc, curr) => {
if (map[curr] === "Bridgeport") {
return acc;
}
acc[curr] = map[curr];
return acc;
}, {});
console.log(updatedMap);