如何在Javascript中的数组对象数组中添加值?

时间:2017-04-28 09:44:29

标签: javascript arrays

对于给定的数组对象

map = [
        {
         "userId":"2345454",
         "socketIds":["asd2324","asdfs3242"]
        },
        {
         "userId":"353453",
         "socketIds":["asdf3456","as234s","sfsdf324"]
        }
      ];

我获得了一个新的套接字ID和一个要添加到地图的用户ID。如何在数组中搜索用户ID。如果套接字ID存在于元素中,则将其推送,或者如果没有元素与提供的userId匹配,则将带有套接字ID和用户ID的新元素添加到数组中?

5 个答案:

答案 0 :(得分:1)

您可以找到索引并更新(如果存在)

var userId = "2345454";
var id= "56";
var map = [
        {
         "userId":"2345454",
         "socketIds":["asd2324","asdfs3242"]
        },
        {
         "userId":"353453",
         "socketIds":["asdf3456","as234s","sfsdf324"]
        }
      ];
      var idx = map.map(function(val){ return val.userId}).indexOf(userId);
      if(idx > -1) {
          map[idx].socketIds.push(id);
      } else {
        map.push({userId: userId, socketIds: [id]});
      }
     console.log(map);  

答案 1 :(得分:0)

var user = map.find(function(ele){return ele.id == userId})
if(user) user.socketIds.push(socketId)

答案 2 :(得分:0)

以下是您应该尝试的内容

var map = [
    {
     "userId":"2345454",
     "socketIds":["asd2324","asdfs3242"]
    },
    {
     "userId":"353453",
     "socketIds":["asdf3456","as234s","sfsdf324"]
    }
];
	  
function inserOrUpdate(newObj){
  var obj = map.find(function (el) {
  	return el.userId==newObj.userId;
  });
  if(obj){
  	obj.socketIds = newObj.socketIds;
  }else{
  	map.push(newObj);
  }
}
  
inserOrUpdate({
"userId":"2345454",
"socketIds":["aaaaaaa","bbbbbbb"]
});

console.log(JSON.stringify(map));
		

答案 3 :(得分:0)

这里的Code也有助于避免在socketIds中出现重复值。

var map = [
    {
     "userId":"2345454",
     "socketIds":["asd2324","asdfs3242"]
    },
    {
     "userId":"353453",
     "socketIds":["asdf3456","as234s","sfsdf324"]
    }
  ];

var idx = map.map(function(val){ return val.userId}).indexOf(paramUserId);
  if(idx > -1) {
        var idxx= map[idx].socketIds.indexOf(paramUserId);

        if(idxx==-1){
            map[idx].socketIds.push(paramSocketId);    
        }
  } else {
    map.push({userId: paramUserId, socketIds: [paramSocketId]});
  }
console.log(map);

答案 4 :(得分:0)

如果用户和套接字不存在,则会添加新用户和套接字,或者如果用户存在,只需将新套接字值推送给现有用户。

var map = [
        {
         "userId":"2345454",
         "socketIds":["asd2324","asdfs3242"]
        },
        {
         "userId":"353453",
         "socketIds":["asdf3456","as234s","sfsdf324"]
        }
      ];

function addOrUpdate(userArray, userId, socketId) {
  const user = userArray.find(usr =>  usr.userId === userId);
  if(user) {
    user.socketIds.push(socketId);
  } else {
    userArray.push({userId: userId, socketIds: [socketId]});
  }

}
addOrUpdate(map, '2345454', '123888');
addOrUpdate(map, '999999', 'sock1');

console.log(map);