Javascript在多维对象/数组中按值查找和删除

时间:2016-06-28 16:42:06

标签: javascript object multidimensional-array

我基本上需要的是在多维数组中查找项目并仅删除它。问题是在这里有多个相同的对象键。

数组示例(从控制台复制):

gameDetails.betsArray = [{
    '1.02': {
        userDetails: {
            socketID: '/#32EZlk6tW03tNgnOAAAA',
            userID: 1
        },
        trigger: 110,
        parseD: 1.02
    }
}, {
    '1.02': {
        userDetails: {
            socketID: '/#32EZlk6tW03tNgnOAAAA',
            userID: 5
        },
        trigger: 881,
        parseD: 1.02
    }
}]

如何制作数组

gameDetails.betsArray[validator.toFloat(betDetails.breakAt)] = {
    userDetails: {
        socketID: socketID,
        userID: connectedUsers[socketID].id
    },
    betAmount: validator.toInt(betDetails.amount),
    breakAt: validator.toFloat(betDetails.breakAt)
};

我想通过key找到对象,即1.02和object.userDetails.userID = 5

我尝试了什么,但它对我没用:

gameDetails.betsArray.map(function (details, key) {
    if (details.userDetails.userID == connectedUsers[socketID].id &&
        details.trigger == validator.toFloat(betDetails.trigger)) {
        delete gameDetails.betsArray[key];
    }
});

怎么可能做?在最后一步中,我想从找到的对象数组中删除数据。

2 个答案:

答案 0 :(得分:2)

尝试使用有效数据结构和Array#filter

的解决方案
[
    {
        "1.02": {
            "userDetails": {
                "socketID": "/#32EZlk6tW03tNgnOAAAA",
                "userID": 1
            },
            "trigger": 110,
            "parseD": 1.02
        }
    },
    {
        "1.02": {
            "userDetails": {
                "socketID": "/#32EZlk6tW03tNgnOAAAA",
                "userID": 5
            },
            "trigger": 881,
            "parseD": 1.02
        }
    }
]

var data = [{ '1.02': { userDetails: { socketID: '/#32EZlk6tW03tNgnOAAAA', userID: 1 }, trigger: 110, parseD: 1.02 } }, { '1.02': { userDetails: { socketID: '/#32EZlk6tW03tNgnOAAAA', userID: 5 }, trigger: 881, parseD: 1.02 } }];

data = data.filter(function (a) {
    return !a['1.02'] || a['1.02'].userDetails.userID !== 5;
});

console.log(data);

答案 1 :(得分:0)

首先,您需要将数据结构更改为有效的javascript数据,例如此类对象数组,然后您可以使用filter()

var obj = [{
  '1.02': {
    userDetails: {
      socketID: '/#32EZlk6tW03tNgnOAAAA',
      userID: 1
    },
    trigger: 110,
    parseD: 1.02
  }
}, {
  '1.02': {
    userDetails: {
      socketID: '/#32EZlk6tW03tNgnOAAAA',
      userID: 5
    },
    trigger: 881,
    parseD: 1.02
  }
}]

var result = obj.filter(function(e) {
  if (e['1.02'] && e['1.02'].userDetails.userID == 5) return e;
});

console.log(result)