从子对象与值匹配的数组中删除对象

时间:2017-01-30 19:47:21

标签: javascript jquery arrays sorting

我目前正在尝试根据查询字符串对某些值进行排序。我能够在此循环中单独定位每个target,但似乎无法从阵列中正确删除它们。如何从target.target删除与targetList匹配的某些值?'

targetList.forEach(function(target, key) {
    var os = getParameterByName('os');

    if (os == "android") {
        if (target.target.includes(":IOS")) {
            targetList.splice(key, 1);
        }
    } else if (os == "ios") {
        if (target.target.includes(":ANDROID")) {
            targetList.splice(key, 1);
        }
    }

    if (target.target.includes(":IOS")) {
        target.target = schools[target.target.replace(":IOS", "").toLowerCase()] + " (iOS)" || target.target;
    }

    if (target.target.includes(":ANDROID")) {
        target.target = schools[target.target.replace(":ANDROID", "").toLowerCase()] + " (Android)" || target.target;
    }

});

targetList包含如下数组:

[
  {
    "target": "t1",
    "datapoints": [
      [
        51.0,
        1483574400.0
      ],
      [
        54.0,
        1485561600.0
      ],
      [
        54.0,
        1485648000.0
      ]
    ]
  },
  {
    "target": "t2",
    "datapoints": [
      [
        56.0,
        1484265600.0
      ],
      [
        70.0,
        1484352000.0
      ],
      [
        71.0,
        1484438400.0
      ],
      [
        51.0,
        1484611200.0
      ]
    ]
  },
]

我尝试做的是,目标符合某些条件.includes()我希望删除整个包含的对象/数组。

1 个答案:

答案 0 :(得分:0)

在我看来,你的代码工作得很好。我已经创建了一个片段,我删除了额外的处理,以显示你已经做了什么。

一旦你从阵列中删除它,你有没有理由对target.target做些什么?你是否在其他地方引用了包含对象?

var targetList = [
  {
    "target": "t1",
    "datapoints": [
      [
        51.0,
        1483574400.0
      ],
      [
        54.0,
        1485561600.0
      ],
      [
        54.0,
        1485648000.0
      ]
    ]
  },
  {
    "target": "t2",
    "datapoints": [
      [
        56.0,
        1484265600.0
      ],
      [
        70.0,
        1484352000.0
      ],
      [
        71.0,
        1484438400.0
      ],
      [
        51.0,
        1484611200.0
      ]
    ]
  },
];

targetList.forEach(function(target, key) {
  if (target.target.includes("t2")) {
    targetList.splice(key, 1);
  }


});
  
console.log(targetList);