gpt4 book ai didi

javascript - 递归比较对象并将重复的键值放入数组

转载 作者:行者123 更新时间:2023-11-29 23:12:06 25 4
gpt4 key购买 nike

我需要迭代三个对象以检查重复项以最终得到一个对象。如果有重复项,我想将它们放入一个数组中,以便用户可以选择最佳值,以便它们最终都以字符串或整数(或带有字符串/整数的对象)结束。它们可能看起来像这样:

const a = {
first_name: 'Tom',
height: {
feet: 5,
inches: 0
}
}
const b = {
first_name: 'Thomas',
last_name: 'Walsh',
email: 'tomwalsh@domain.com',
height: {
feet: 6,
inches: 0
}
}
const c = {
email: 'tomwalsh@sample.edu'
}

结果是这样的:

const result = {
first_name: ['Tom', 'Thomas'],
last_name: 'Walsh',
email: ['tomwalsh@domain.com', 'tomwalsh@sample.edu'],
height: {
feet: [5, 6],
inches: 0
}
}

我不知道 abc 是否是 key 的权限,所以我必须假设一组未知的键/值对,但绝对很小(不超过 20 对,只有 2-3 对超过 3 层深,并且每个层最多有 4-5 个键/值对。

我可以创建一个新对象,递归地迭代这三个对象,然后转储值或创建一个值数组,但这似乎效率不高。有什么建议吗?

如果需要,我在项目中加入了 lodash。谢谢!

最佳答案

由于某些对象中可能缺少嵌套键,您可以通过 lodash 的 _.mergeWith() 合并它们,并将重复项收集到数组中:

const a = {"first_name":"Tom","height":{"feet":5,"inches":0}}
const b = {"first_name":"Thomas","last_name":"Walsh","email":"tomwalsh@domain.com","height":{"feet":6,"inches":0}}
const c = {"email":"tomwalsh@sample.edu"}

const shouldCollect = (s) => _.negate(_.overSome([
_.isUndefined,
_.isObject,
_.partial(_.eq, s)
]))


const mergeDupes = (...args) => _.mergeWith({}, ...args, (o, s) => {
if(_.isArray(o)) return _.uniq([...o, s]);
if(shouldCollect(s)(o)) return [o, s];
})

const result = mergeDupes(a, b, c)

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

如果你想删除不重复的属性,你可以通过递归 _.transform() 清理对象:

const a = {"first_name":"Tom","height":{"feet":5,"inches":0}}
const b = {"first_name":"Thomas","last_name":"Walsh","email":"tomwalsh@domain.com","height":{"feet":6,"inches":0}}
const c = {"email":"tomwalsh@sample.edu"}

const shouldCollect = (s) => _.negate(_.overSome([
_.isUndefined,
_.isObject,
_.partial(_.eq, s)
]))

const omitNonDuplicates = obj =>
_.transform(obj, (a, v, k) => {
if (_.isArray(v)) a[k] = v;
else if (_.isObject(v)) {
const clean = omitNonDuplicates(v);
if(!_.isEmpty(clean)) a[k] = clean;
return;
}
});

const mergeDupes = (...args) => omitNonDuplicates(_.mergeWith({}, ...args, (o, s) => {
if(_.isArray(o)) return _.uniq([...o, s]);
if(shouldCollect(s)(o)) return [o, s];
}))

const result = mergeDupes(a, b, c)

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

关于javascript - 递归比较对象并将重复的键值放入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53710404/

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