0

假设我有一个这样的数组:

arrayOfObject = [{item: {this: is,  that: is}}, {item2: {this: is, that: is}}]

我正在尝试访问 item 和 item2 而不必使用 0/1 索引。我希望能够说 arrayOfObjects[item] 进入对象。这可能吗?

4

4 回答 4

1

var arrayOfObject = [{
    "item": {
        "this": "is",
        "that": "is"
    }
}, {
    "item2": {
        "this": "is",
        "that": "is"
    }
}];

var itemObject = {};
arrayOfObject.forEach(function(value) {
    var filterObject = Object.keys(value).filter(val => val.indexOf("item") != -1);
    if (filterObject.length > 0) {
        filterObject.forEach(key => {
            itemObject[key] = itemObject[key] || [];
            itemObject[key].push(value[filterObject[0]]);
        });
    }
});

console.log(itemObject.item); //item
console.log(itemObject.item2); //item

于 2018-08-30T17:14:34.513 回答
1

您可以使用 Array.find。

arrayOfObject = [{
  item: {
    this: 'is',
    that: 'is'
  }
}, {
  item2: {
    this: 'is',
    that: 'is'
  }
}]

console.log(arrayOfObject.find(ob => ob['item']));
console.log(arrayOfObject.find(ob => ob['item2']));

于 2018-08-30T17:06:30.967 回答
0

Yeah sure it is possible:

var result = arrayOfObject.map(a => a.item);

or

var result = arrayOfObject.map(a => a.item2);
于 2018-08-30T17:11:00.383 回答
0

您不能完全做到这一点,但您可以将数组“转换”为对象,然后使用键访问值:

arrayOfObject = [{ item: { this: "a", that: "b" } }, { item2: { this: "c", that: "d" } }]

const arrayToObject = arrayOfObject.reduce((r,c) => Object.assign(r,c), {})

console.log(arrayToObject['item'])
console.log(arrayToObject['item2'])

在上面的代码片段中,我们将arrayOfObject数组转换对象,然后简单地通过键访问值。

否则,您尝试做的事情是不可能的,因为您只能通过索引或某种函数访问数组中的值,该函数将遍历它并为您获取条目等find

于 2018-08-30T17:28:54.243 回答