这种比较有点奇怪,因为我有以下格式:
首选项对象:
{
models: [
{... attributes: {} },
{... attributes: {} },
{... attributes: {} }
]
}
数据数组:
[{}, {}, {}]
我有这个对象
,其中包含更多 对象
的数组
,其键名为< em>属性。
我的目标:
我的目标是使用 Underscore.JS 查看数据数组中的哪些项目不作为模型数组中的属性键的值存在。
黑客尝试:
这绝对不是我想要的编码方式,但是 localStorageLayers
是数据数组,layerPrefs
是首选项Object就是上面的标签。
_.each(localStorageLayers, (localLayer) => {
var layerWasLoaded = false;
_.each(layerPrefs.models, (layerPref) => {
if (_.isEqual(layerPref.attributes, localLayer)) {
layerWasLoaded = true;
// Don't do anything
}
})
if (layerWasLoaded == false) {
// Do stuff
}
})
最佳答案
您可以过滤
localStorageLayers
到一个子集,其中localLayer
被发现等于none(否定some
)的layerPrefs.models
对象与其attributes
属性相比。
我不使用lodash
,但result
应该只包含在layerPrefs.models中没有找到相等性的
.localStorageLayers
const layerPrefs = {
models: [
{attributes: {foo: "foo"} },
{attributes: {foo: "bar"} },
{attributes: {baz: "baz"} }
]
};
const localStorageLayers = [
{foo: "foo"}, {hot: "dog"}, {hot: "dog"}, {baz: "baz"}
];
const result = _.filter(localStorageLayers, localLayer =>
!_.some(layerPrefs.models, layerPref =>
_.isEqual(layerPref.attributes, localLayer)
)
);
console.log(result);
// Remove duplicates
const noDupes = _.uniqBy(result, _.isEqual);
console.log(noDupes);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.5/lodash.min.js"></script>
您可以通过使用 !_.isEqual
执行 _.every
来反转每个 localLayer
的计算。
使用看起来更清晰的那个。
const result = _.filter(localStorageLayers, localLayer =>
_.every(layerPrefs.models, layerPref =>
!_.isEqual(layerPref.attributes, localLayer)
)
);
关于javascript - 使用下划线确定对象是否存在于深度嵌套的对象数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49097700/