在对象中添加到数组时避免if..else梯形图

时间:2014-01-27 10:27:48

标签: javascript

有没有办法避免以下代码中的if..else条件并在一行中执行此操作?

var myObject = {},
    data = ["Chennai", "Thoothukkudi", "Madurai",
            "Coimbatore", "Trichy", "Salem", "Tirunelveli",
            "Erode", "Vellore", "Tiruppur"];

data.forEach(function(currentCity) {
    if (currentCity[0] in myObject) {
        myObject[currentCity[0]].push(currentCity);
    } else {
        myObject[currentCity[0]] = [currentCity];
    }
});

console.log(myObject);

输出

{ C: [ 'Chennai', 'Coimbatore' ],
  T: [ 'Thoothukkudi', 'Trichy', 'Tirunelveli', 'Tiruppur' ],
  M: [ 'Madurai' ],
  S: [ 'Salem' ],
  E: [ 'Erode' ],
  V: [ 'Vellore' ] }

问题是,我必须在我的代码中的许多地方进行if..else检查。如果我在8个地方这样做,它最多可以增加40行。所以,我正在寻找一种方法来编写一行。

在Python中,有一些叫做defaultdict的东西,普通的dict也可以和setdefault函数一起使用。有没有优雅和简短(少行数)的方法呢?

3 个答案:

答案 0 :(得分:4)

像这样:

myObject[currentCity[0]] = myObject[currentCity[0]] || [];
myObject[currentCity[0]].push(currentCity);

答案 1 :(得分:2)

您可以将这些行添加到单独的函数中,然后您只需在每个实例中调用一次:

function wrangleCity(currentCity, myObject) {
  if (currentCity[0] in myObject) {
    myObject[currentCity[0]].push(currentCity);
  } else {
    myObject[currentCity[0]] = [currentCity];
  }
}

data.forEach(function (currentCity) {
  wrangleCity(currentCity, myObject);
});

Demo

答案 2 :(得分:0)

    var myObject = {},
        data = ["Chennai", "Thoothukkudi", "Madurai",
                "Coimbatore", "Trichy", "Salem", "Tirunelveli",
                "Erode", "Vellore", "Tiruppur"],

    data.map(v => {

         myObject.hasOwnProperty(v[0]) 
         ? myObject[v[0]].push(v) 
         : myObject[v[0]] = [v] 
    });

console.log("final result",myObject)

Array.Prototype.forEach比较? Array.Prototype.map使用返回值并实际返回相同大小的新数组。