【问题标题】:How to compare two json array with TypeScript?如何将两个 json 数组与 TypeScript 进行比较?
【发布时间】:2017-02-23 20:00:04
【问题描述】:

例如我有这个dataInput json:

dataInput= [
    {text: 'text1'},
    {text: 'text2'},
    {text: 'text3'}
];

我想将其与以下内容进行比较:

dataInputUpdated= [
  {text: 'text1', info: 'something'},
  {text: 'text2'},
  {text: 'text3'}
];

如何将它们与 Typescript 进行比较?有没有等价的方法?这是对象数组,所以我想知道它在任何更改时都不相等。

【问题讨论】:

  • 数组中对象的顺序是否总是相同的?
  • 是的,顺序是一样的。更改将是每个对象内部的某些内容,例如属性值的更改或添加的属性

标签: typescript


【解决方案1】:

您可以使用JSON.stringify 方法进行比较。这是一个示例:

let dataInput= [
    {text: 'text1'},
    {text: 'text2'},
    {text: 'text3'}
];

let dataInputUpdated= [
  {text: 'text1', info: 'something'},
  {text: 'text2'},
  {text: 'text3'}
];

let areSame: boolean = JSON.stringify(dataInput) === JSON.stringify(dataInputUpdated);

alert(areSame); // returns false

【讨论】:

    猜你喜欢
    • 2021-02-01
    • 2014-10-27
    • 2019-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 2015-07-15
    • 2014-04-01
    相关资源
    最近更新 更多