我有两个对象,如果两个道具具有相同的键,我需要合并它们并连接字符串

发布于 2025-01-11 13:44:34 字数 481 浏览 0 评论 0原文

我有两个对象,如果两个道具具有相同的键,我需要合并它们并连接字符串 注意:我正在使用 lodash.js

obj1 = {
  name: 'john', 
  address: 'cairo'
}

obj2 = {
  num : '1', 
  address: 'egypt'
}

我需要合并的对象如下:

merged = {name:"john", num: "1", address:"cairo,Egypt"}

当我尝试使用时,地址属性的问题 _.defaults(obj1,obj2) 或者 _.merge(obj1,obj2)

地址值将是 obj2 内的地址 prop 的值 所以我需要一种方法来合并两个对象并连接每个对象中的两个地址道具。

I have two objects and i need to merge them and concat strings if two props have the same key
note: I'm using lodash.js

obj1 = {
  name: 'john', 
  address: 'cairo'
}

obj2 = {
  num : '1', 
  address: 'egypt'
}

I need the merged object to be like:

merged = {name:"john", num: "1", address:"cairo,Egypt"}

the issue with address prop when I'm trying to use
_.defaults(obj1,obj2)
or
_.merge(obj1,obj2)

the address value will be the value of the address prop inside obj2
so I need a way to merge the two objects and concat the two address props in each object.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

此岸叶落 2025-01-18 13:44:34

试试这个:

    function merge(obj1, obj2) {
      let merged = {
        ...obj1,
        ...obj2
      };
      Object.keys(obj1).filter(k => obj2.hasOwnProperty(k)).forEach((k) => {
        merged[k] = obj1[k] + "," + obj2[k]
      })
      return merged
    }

    obj1 = {
      name: 'john',
      address: 'cairo'
    }

    obj2 = {
      num: '1',
      address: 'egypt'
    }

    console.log(merge(obj1, obj2))

Try this:

    function merge(obj1, obj2) {
      let merged = {
        ...obj1,
        ...obj2
      };
      Object.keys(obj1).filter(k => obj2.hasOwnProperty(k)).forEach((k) => {
        merged[k] = obj1[k] + "," + obj2[k]
      })
      return merged
    }

    obj1 = {
      name: 'john',
      address: 'cairo'
    }

    obj2 = {
      num: '1',
      address: 'egypt'
    }

    console.log(merge(obj1, obj2))

少女七分熟 2025-01-18 13:44:34

您甚至不需要 lodash。您可以轻松地为此创建自己的函数。您可以这样做:

  • new Set - 查找两个输入对象中所有唯一的
  • for...of - 迭代唯一的上面计算出的键
function mergeObjects(obj1, obj2) {
  let merged = {};
  for (const property of [...new Set([...Object.keys(obj1),...Object.keys(obj2)])]) {
    if(obj1[property]) merged[property] = obj1[property];
    if(obj2[property]) merged[property] = merged[property] ? `${merged[property]},${obj2[property]}` : obj2[property];
  }
  return merged;
}

const obj1 = { name: 'john', address: 'cairo' };
const obj2 = { num : '1', address: 'egypt' };

const mergedObj = mergeObjects(obj1, obj2);
console.log(mergedObj);

You don't even need lodash. You can easily create you own function for that. You can do it like this:

  • new Set - to find all unique keys across both input objects
  • for...of - to iterate over unique keys calculated above

function mergeObjects(obj1, obj2) {
  let merged = {};
  for (const property of [...new Set([...Object.keys(obj1),...Object.keys(obj2)])]) {
    if(obj1[property]) merged[property] = obj1[property];
    if(obj2[property]) merged[property] = merged[property] ? `${merged[property]},${obj2[property]}` : obj2[property];
  }
  return merged;
}

const obj1 = { name: 'john', address: 'cairo' };
const obj2 = { num : '1', address: 'egypt' };

const mergedObj = mergeObjects(obj1, obj2);
console.log(mergedObj);

沉默的熊 2025-01-18 13:44:34
function mergeObjects(objArr) {
    const newObj = {};

    objArr.forEach((element) => {
        const keys = Object.keys(element);
        keys.forEach((key) => {
            if (newObj[key]) newObj[key] = newObj[key] + "," + element[key];
            else newObj[key] = element[key];
        });
    });
    return newObj;
}

const obj1 = {name: 'john',   address: 'cairo'}

const obj2 = {  num : '1',   address: 'egypt'}
console.log(mergeObjects([obj1, obj2]));

这样您就可以合并任意数量的对象!

function mergeObjects(objArr) {
    const newObj = {};

    objArr.forEach((element) => {
        const keys = Object.keys(element);
        keys.forEach((key) => {
            if (newObj[key]) newObj[key] = newObj[key] + "," + element[key];
            else newObj[key] = element[key];
        });
    });
    return newObj;
}

const obj1 = {name: 'john',   address: 'cairo'}

const obj2 = {  num : '1',   address: 'egypt'}
console.log(mergeObjects([obj1, obj2]));

This way you can merge any number of objects!

何止钟意 2025-01-18 13:44:34

您可以使用 _.mergeWith() 将特定键的值连接到数组,然后使用 _.mapValues() 将数组连接到字符串:

const { mergeWith, mapValues, uniq, join } = _;

const fn = (predicate, ...objs) => mapValues(
  // merge the objects
  mergeWith(
    {}, 
    ...objs, 
    // handle the keys that you want to merge in a uniqe way
    (a = [], b = [], key) => predicate(key) ? a.concat(b) : undefined
  ),
  // transform the relevant keys' values to a uniqe strings
  (v, key) => predicate(key) ? uniq(v).join(', ') : v
);

const obj1 = { name: 'john', address: 'cairo' };
const obj2 = { num : '1', address: 'egypt' };

const result = fn(key => key === 'address', obj1, obj2);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

You can use _.mergeWith() to concat the values of specific keys to arrays, and then use _.mapValues() to join the arrays to strings:

const { mergeWith, mapValues, uniq, join } = _;

const fn = (predicate, ...objs) => mapValues(
  // merge the objects
  mergeWith(
    {}, 
    ...objs, 
    // handle the keys that you want to merge in a uniqe way
    (a = [], b = [], key) => predicate(key) ? a.concat(b) : undefined
  ),
  // transform the relevant keys' values to a uniqe strings
  (v, key) => predicate(key) ? uniq(v).join(', ') : v
);

const obj1 = { name: 'john', address: 'cairo' };
const obj2 = { num : '1', address: 'egypt' };

const result = fn(key => key === 'address', obj1, obj2);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文