0

私は Javascript が初めてで、私が書いた関数に問題があります。私は array.reduce() を使用して仕事をしていますが、Windows では失敗しています (Mac でのテストは正常に動作します)。

私が持っているファイルは次のようにフォーマットされています:

ford.car.focus.transmission=standard
ford.car.focus.engine=four-cylinder
ford.car.focus.fuel=gas

ford.car.taurus.transmission=automatic
ford.car.taurus.engine=V-8
ford.car.taurus.fuel=diesel

purchased=Ford Taurus

構造を次のようにしたいと思います。

{ ford:
  { car:
    { focus:
      {
        transmission: 'standard',
        engine: 'four-cylinder',
        fuel: 'gas'
      }
    }
    { taurus:
      {
        transmission: 'automatic',
        engine: 'V-8',
        fuel: 'diesel'
      }
    }
  }
  purchased: 'Ford Taurus'
}

ファイル行を配列に格納し、「\ n」で分割しています。次のようにグローバルオブジェクトを渡し、ループで呼び出されるメソッドを作成しようとしています:

var hash = {};
var array = fileData.toString().split("\n");
for (i in array) {
  var tmp = array[i].split("=");
  createNestedObjects(tmp[0], tmp[1], hash);
}

私の現在の機能は次のようになります。

function create_nested_object(path, value, obj) {
  var keys = path.split('.');
  keys.reduce(function(o, k) {
    if (k == keys[keys.length-1]) {
      return o[k] = value;
    } else if (o[k]) {
      return o[k];
    } else {
      return o[k] = {};
    }
  }, obj);
}

これを for ループにしたいと思います。次のような新しいコードがあります (array.reduce() コードを変換してみました):

function create_nested_object(path, value, obj) {
  var keys = path.split('.');

  for (var i = 0; i < keys.length; i++) {
    if (keys[i] == keys[keys.length-1]) {
      obj[keys[i]] = value;
    } else if (obj[keys[i]] == keys[i]) {
      obj;
    } else {
      obj = obj[keys[i]] = {};
    }
  }
}

ただし、各ネストの最後のアイテムのみを返します。

{
  "ford": {
    "car": {
      "taurus": {
        "fuel": "diesel"
      }
    }
  },
  "purchased": "Ford Taurus"
}

何かが足りないことはわかっていますが、何が悪いのかわかりません。どんな助けでも大歓迎です!

関連する質問: Javascript - INI ファイルをネストされた連想配列に解析する

4

2 に答える 2

0

The EOL answer is a good one, so I am giving it the upvote. In answer to my question about why my function was failing is that it had nothing to do with Windows. The issue was that the file on the Windows machine had some duplication in the keys that caused the function to fail.

ford.car.focus.transmission=standard
ford.car.focus.engine=four-cylinder
ford.car.focus.engine.type=big
ford.car.focus.fuel=gas

In the above example, the engine property was being set as a value (four-cylinder), and then on the next iteration of the function it was trying to deal with the fact that there was another (nest) for engine (type=big). Because an object can't have the same key twice, it was causing the function to die.

Thanks to everyone for responding!

于 2016-04-27T13:48:41.403 に答える