使用Object.keys作为对象数组

时间:2016-05-27 07:12:42

标签: javascript jquery

我使用Object.keys对我的对象数组进行一些键分配。但它为每次迭代返回了唯一的对象,所以我的4个项目变为2.任何方法可以避免这种情况?

var cityIdmap = {};
var bpidmap = {
  '7': {
    cityid: 2,
    bpid: 7,
    name: 'Puduraya',
    time: '+00:00',
    sbpid: 50169
  },
  '11': {
    cityid: 1,
    bpid: 11,
    name: 'Golden Mile Tower',
    time: '+00:00',
    sbpid: 50172
  },
  '12': {
    cityid: 2,
    bpid: 12,
    name: 'Berjaya Times Square',
    time: '+00:00',
    sbpid: 50171
  },
  '66': {
    cityid: 1,
    bpid: 66,
    name: 'Textile Centre',
    time: '+00:00',
    sbpid: 50170
  }
};

Object.keys(bpidmap).forEach(function(item) {
  var bp = bpidmap[item];
  cityIdmap[bp.cityid] = {};
  cityIdmap[bp.cityid][bp.bpid] = bp;
});

document.write(JSON.stringify(cityIdmap));

2 个答案:

答案 0 :(得分:0)

添加对象已初始化的check

Object.keys(bpidmap).forEach(function(item) {
  var bp = bpidmap[item];
  if (typeof cityIdmap[bp.cityid] === 'undefined') cityIdmap[bp.cityid] = {};
  cityIdmap[bp.cityid][bp.bpid] = bp;
});

答案 1 :(得分:0)

您可以array使用cityIdmap[bp.cityid]代替object

var cityIdmap = {};
var bpidmap = {
  '7': {
    cityid: 2,
    bpid: 7,
    name: 'Puduraya',
    time: '+00:00',
    sbpid: 50169
  },
  '11': {
    cityid: 1,
    bpid: 11,
    name: 'Golden Mile Tower',
    time: '+00:00',
    sbpid: 50172
  },
  '12': {
    cityid: 2,
    bpid: 12,
    name: 'Berjaya Times Square',
    time: '+00:00',
    sbpid: 50171
  },
  '66': {
    cityid: 1,
    bpid: 66,
    name: 'Textile Centre',
    time: '+00:00',
    sbpid: 50170
  }
};

Object.keys(bpidmap).forEach(function(item) {
  var bp = bpidmap[item];
  cityIdmap[bp.cityid] = cityIdmap[bp.cityid] || []; //use array instead of object
  var temp = {};
  temp[bp.bpid] = bp;
  cityIdmap[bp.cityid].push(temp);
});