我可以为对象添加动态密钥吗?

时间:2016-10-16 20:56:41

标签: javascript object key

函数会是什么样的"键"输入对象?我一直在研究这个话题,但无法找到任何好的答案。

所以,如果我有一个输入对象......

public download extends AsyncTask

1 个答案:

答案 0 :(得分:0)

您可以使用创建新对象的函数并使用所需的键返回项目。

版本为Array#forEach

function getKeyedArray(array, callback) {
    var object = Object.create(null);
    array.reduce(function (a) {
        var key = callback(a);
        object[key] = object[key] || [];
        object[key].push(a);
    });
    return object;
}

var fruits = [{ fruit: "apple", taste: "sour" }, { fruit: "cherry", taste: "sweet", color: "red" }];

console.log(getKeyedArray(fruits, function (i) { return i.fruit; }));
console.log(getKeyedArray(fruits, function (i) { return i.taste.length; }));

版本为Array#reduce

function getKeyedArray(array, callback) {
    return array.reduce(function (r, a) {
        var key = callback(a);
        r[key] = r[key] || [];
        r[key].push(a);
        return r;
    }, Object.create(null));
}

var fruits = [{ fruit: "apple", taste: "sour" }, { fruit: "cherry", taste: "sweet", color: "red" }];

console.log(getKeyedArray(fruits, function (i) { return i.fruit; }));
console.log(getKeyedArray(fruits, function (i) { return i.taste.length; }));