javascript从数组

时间:2017-04-02 15:10:31

标签: javascript angularjs arrays dictionary

我有一个像这样的数组

propertiesToCheck: [
    {name: 'name', type: 'type', enabled: true},
    {
        name: 'name2',
        type: 'type2',
        templateUrl: 'something.html',
        preferences: {
            places: [place1, place2,...],
            placesDict: ????
        },
        enabled: true
    }
]

places数组中有包含id,name等的对象。现在我想创建一个看起来像placesDict的字典{place1.id: 0, place2.id: 0, ...},因此所有值都将设置为我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

var placesDict = {};
propertiesToCheck[1].preferences.places.forEach(place => {
  placesDict[place.id] = 0;
});

同样的事情,但使用函数定义而不是箭头函数。

var placesDict = {};
propertiesToCheck[1].preferences.places.forEach(setPlace);

function setPlace (place) {
  placesDict[place.id] = 0; 
}

要将此功能附加到preferences对象的方法:

propertiesToCheck: [
    {name: 'name', type: 'type', enabled: true},
    {
        name: 'name2',
        type: 'type2',
        templateUrl: 'something.html',
        preferences: {
            places: [place1, place2,...],
            placesDict: () => {
              newDict = {}; 
              propertiesToCheck[1].preferences.places.forEach(place => newDict[place.id] = 0);
              return newDict;
            }
        },
        enabled: true
    }
]

console.log(propertiesToCheck[1].preferences.placesDict()); // {place1.id: 0, place2.id: 0, ...}

将属性placesDict设置为等于函数返回值:

propertiesToCheck: [
    {name: 'name', type: 'type', enabled: true},
    {
        name: 'name2',
        type: 'type2',
        templateUrl: 'something.html',
        preferences: {
            places: [place1, place2,...],
            placesDict: createDict()
        },
        enabled: true
    }
]

function createDict() {
  var placesDict = {};
  propertiesToCheck[1].preferences.places.forEach(place => {
    placesDict[place.id] = 0; 
  }); 
}

我希望这有帮助。

答案 1 :(得分:0)

例如在Ramda中:

var createDict = R.pipe(R.pluck('id'), R.map(R.pair(R.__, 0)), R.fromPairs);

var places = [{ id: 'place1id' }, { id: 'place2id' }];
var placesDict = createDict(places);

// {"place1id": 0, "place2id": 0}