gpt4 book ai didi

javascript - 使用下划线确定对象是否存在于深度嵌套的对象数组中?

转载 作者:行者123 更新时间:2023-12-03 02:22:23 25 4
gpt4 key购买 nike

这种比较有点奇怪,因为我有以下格式:

首选项对象:

{ 
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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com