在javascript中递归合并对象

时间:2018-01-17 06:19:39

标签: javascript arrays object lodash

我目前正在处理一个带有react的项目,我在使用setState方法时遇到了合并两个对象的问题。我有两个类似于

的对象
person1 = {
    name: 'ramya',
    age: 21,
    gender: 'f',
    skills:{
        technicalSkills: {
            languages: ['C', 'C++', 'Java'],
            operatingSystems: ['Unix', 'Linux']
        },
        linguisticSkills: {
            toSpeak: ['English', 'Tamil'],
            toRead: ['English']
        }
    },
}

obj2 = {
    skills: {
        linguisticSkills: {
            toRead: ['English', 'Tamil']
        }
    }
}

我想改变人1的技能状态。语言技能为

linguisticSkills: {
                toSpeak: ['English', 'Tamil'],
                toRead: ['English', 'Tamil']
} 

skills.linguisticSkills.toSpeakskills.linguisticSkills.toRead不断变化,即添加或删除项目。每当它发生变化时,如何在setState中合并person1和obj2,以便最终处于正确的状态?

更新 _.merge因为这样的情况而失败:

person1 = {
        name: 'ramya',
        age: 21,
        gender: 'f',
        skills:{
            technicalSkills: {
                languages: ['C', 'C++', 'Java'],
                operatingSystems: ['Unix', 'Linux']
            },
            linguisticSkills: {
                toSpeak: ['English', 'Tamil'],
                toRead: ['English', 'Tamil', 'Telugu']
            }
        },
    }

    obj2 = {
        skills: {
            linguisticSkills: {
                toRead: ['English', 'Tamil']
            }
        }
    }

它给出与人1相同的结果,而

{
        name: 'ramya',
        age: 21,
        gender: 'f',
        skills:{
            technicalSkills: {
                languages: ['C', 'C++', 'Java'],
                operatingSystems: ['Unix', 'Linux']
            },
            linguisticSkills: {
                toSpeak: ['English', 'Tamil'],
                toRead: ['English', 'Tamil']
            }
        },
    }
预计

2 个答案:

答案 0 :(得分:4)

Lodash的_.merge()是递归的。如果您需要对合并过程进行更精细的控制,可以使用_.mergeWith()

    if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = refrenceViewController as! UIImagePickerControllerDelegate & UINavigationControllerDelegate
        imagePicker.sourceType = .photoLibrary;
        imagePicker.allowsEditing = true
        refrenceViewController.present(imagePicker, animated: true, completion: nil)

    }
const person1 = {"name":"ramya","age":21,"gender":"f","skills":{"technicalSkills":{"languages":["C","C++","Java"],"operatingSystems":["Unix","Linux"]},"linguisticSkills":{"toSpeak":["English","Tamil"],"toRead":['English', 'Tamil', 'Telugu']}}}

const obj2 = {"skills":{"linguisticSkills":{"toRead":["English","Tamil"]}}}

const result = _.mergeWith({}, person1, obj2, (objValue, srcValue) => {
  if( _.isArray(srcValue)) {
    return srcValue;
  }
});

console.log(result);

答案 1 :(得分:0)

查看https:How to deep merge instead of shallow merge?

/**
 * Simple object check.
 * @param item
 * @returns {boolean}
 */
export function isObject(item) {
  return (item && typeof item === 'object' && !Array.isArray(item));
}

/**
 * Deep merge two objects.
 * @param target
 * @param ...sources
 */
export function mergeDeep(target, ...sources) {
  if (!sources.length) return target;
  const source = sources.shift();

  if (isObject(target) && isObject(source)) {
    for (const key in source) {
      if (isObject(source[key])) {
        if (!target[key]) Object.assign(target, { [key]: {} });
        mergeDeep(target[key], source[key]);
      } else {
        Object.assign(target, { [key]: source[key] });
      }
    }
  }

  return mergeDeep(target, ...sources);
}

// Code copied from linked Stack Overflow question
// https://stackoverflow.com/questions/27936772/how-to-deep-merge-instead-of-shallow-merge
// Answer by Salakar:
// https://stackoverflow.com/users/2938161/salakar