如何更新JSON数据

时间:2019-01-29 22:49:50

标签: javascript arrays json loops object

我想得到更新两个json数据的结果,第二个json从第一个json更新了现有数据,并且它也有新数据,这些是我的结构:

var origin = {
  "allTest": [
    {
      "testName": "A",
      "platform": [{"name": "chrome", "area": ["1"]}]
    },
    {
      "testName": "B",
      "platform": [{"name": "Edge", "area": ["2"]}]
    }
  ]
};

var updated = {
  "allTest": [
    {
      "testName": "A",
      "platform": [{"name": "chrome", "area": ["1"]}]
    },
    {
      "testName": "B",
      "platform": [{"name": "Safari", "area": ["3"]}]
    },
    {
      "testName": "C",
      "platform": [{"name": "IE", "area": ["4"]}]
    }
  ]
}

var result = origin.allTest.concat(updated.allTest);
console.log(result);

结果:

  [ { testName: 'A', platform: [ [Object] ] },
  { testName: 'B', platform: [ [Object] ] },
  { testName: 'A', platform: [ [Object] ] },
  { testName: 'B', platform: [ [Object] ] },
  { testName: 'C', platform: [ [Object] ] } ]

但这不是当前更新,我想这样更新原始数据:

预期结果:

{
  "allTest": [
    {
      "testName": "A",
      "platform": [{"name": "chrome", "area": ["1"]}]
    },
    {
      "testName": "B",
      "platform": [{"name": "Edge", "area": ["2"]},{"name": "Safari", "area": ["3"]}]
    },
    {
      "testName": "C",
      "platform": [{"name": "IE", "area": ["4"]}]
    }
  ]
}

能帮我解决一下吗?我是新手,谢谢

4 个答案:

答案 0 :(得分:0)

使用JsonPatch。根据所使用的技术,您会找到不同的工具来实现此目的。 JsonPatch文档基本上就是描述原始文档中的更改的Json。

答案 1 :(得分:0)

您可以像这样使用散布运算符:

<div className="jumbotron" ref={this.divElement}></div>

答案 2 :(得分:0)

您可以使用一个函数来递归地遍历目标对象并适当地添加它。

据我对您的结构的了解,如果testname相等,则需要特定的逻辑来处理平台的并置。我在此处编写了一个快速功能作为示例,但是此功能不检查重复项。原谅我的草率代码,我也是javascript新手。

var origin = {
  "allTest": [
    {
      "testName": "A",
      "platform": [{"name": "chrome", "area": ["1"]}]
    },
    {
      "testName": "B",
      "platform": [{"name": "Edge", "area": ["2"]}]
    }
  ]
};

var updated = {
  "allTest": [
    {
      "testName": "A",
      "platform": [{"name": "chrome", "area": ["1"]}]
    },
    {
      "testName": "B",
      "platform": [{"name": "Safari", "area": ["3"]}]
    },
    {
      "testName": "C",
      "platform": [{"name": "IE", "area": ["4"]}]
    }
  ]
}

function concatJson(source, target)
{
    var result = target;

     for (var i in source.allTest)
     {
         var found = false;
         for (var j in result.allTest)
         {
             //if the testname is the same we need to concat the platform
             if(!found && source.allTest[i].testName == result.allTest[j].testName)
             {
                result.allTest[i].platform = source.allTest[i].platform.concat(result.allTest[j].platform)
                found = true;
             }
        }
        if(!found)
        {
            //no match found so we'll add the tuple to the list
            result.allTest = result.allTest.concat(source.allTest[i]);
        }
    }
    return result;
}

var result = concatJson(updated, origin);
console.log(JSON.stringify(result, null, 4));

答案 3 :(得分:0)

这是一种不使用库的解决方案,但它不是动态的,因此仅针对您的用例进行了量身定制。

我被封锁了,无法将其设置为最佳状态,因此欢迎您提供任何反馈意见:)

const origin = {
  allTest: [
    {
      testName: 'A',
      platform: [{ name: 'chrome', area: ['1'] }],
    },
    {
      testName: 'B',
      platform: [{ name: 'Edge', area: ['2'] }],
    },
  ],
}

const updated = {
  allTest: [
    {
      testName: 'A',
      platform: [{ name: 'chrome', area: ['1'] }],
    },
    {
      testName: 'B',
      platform: [{ name: 'Safari', area: ['3'] }],
    },
    {
      testName: 'C',
      platform: [{ name: 'IE', area: ['4'] }],
    },
  ],
}

const findAndMergePlatforms = (array, item) =>
  array
    .filter(o => o.testName === item.testName)
    .map(o => ({ ...o, platform: [...o.platform, ...item.platform] }))

const removeExisting = (array, item) =>
  array.filter(o => o.testName !== item.testName)

const removeDuplicatePlatforms = platforms =>
  platforms.reduce(
    (acc, curr) =>
      acc.filter(({ name }) => name === curr.name).length > 0
        ? acc
        : [...acc, curr],
    []
  )

const mergedAllTests =
  // Merge "allTest" objects from both arrays
  [...origin.allTest, ...updated.allTest]

    // Merge the "platform" properties
    .reduce((acc, curr) => {
      const found = findAndMergePlatforms(acc, curr)
      acc = removeExisting(acc, curr)
      return found.length !== 0 ? [...acc, ...found] : [...acc, curr]
    }, [])

    // Remove platform duplicates
    .map(({ testName, platform }) => ({
      testName,
      platform: removeDuplicatePlatforms(platform),
    }))

const result = { allTest: mergedAllTests }

const util = require('util')
console.log(util.inspect(result, { showHidden: false, depth: null }))

编辑: 添加了注释,并将结果固定为包含allTest对象。