我可以将对象和数组放在另一个数组中吗?

时间:2015-08-17 02:24:50

标签: javascript angularjs

我有两个对象,我想在一个对象中组合在一起,然后将它们放在一个数组中。

vm.data = {};
vm.category_name_image = [] ;

getProductFunc=function(){

        $http.get(ConfigCnst.apiUrl+'?route=categories').success(function (res) {
            //console.log(res);
            var sub_category = res;
            console.log(sub_category);
            var bagmankey = '-JweP7imFLfnh96iwn-c';
            //console.log(bagmankey);
            angular.forEach(sub_category, function (value, key) {
                if (value.parentKey == bagmankey ) {
                // where i loop         
                    vm.data.name = value.name;
                    vm.data.picture = value.image;

                    var selected = {
                            vm.data.name,
                            vm.data.picture
                        } // Where I group the two.

                        vm.category_name_image.push(seleted);
                        // where i want to place the both.


                }

            });


            });
    }

当我将vm.data.name和vm.data.picture放在所选对象中时,我似乎遇到了错误。

我希望我的输出如下:[{name,picture},{name,picture},{name,picture}]

4 个答案:

答案 0 :(得分:3)

如果没有名称,则无法创建对象属性:

//object with properties 'name' & 'picture'
var selected = {
    name: vm.data.name,
    picture: vm.data.picture
}

或者你可以使用数组,如果你真的只需要使用数据(糟糕的方式):

var selected = [
    vm.data.name,
    vm.data.picture
]

答案 1 :(得分:1)

Javascript对象是键值对。构造对象时缺少密钥

var selected = {
    name: vm.data.name,
    picture: vm.data.picture
} // Where I group the two.

您可以在不使用selected

的情况下直接推送
vm.category_name_image.push({
    name: vm.data.name,
    picture: vm.data.picture
});

答案 2 :(得分:1)

你的例子中有一个拼写错误。

var selected = {
    vm.data.name,
    vm.data.picture
}; // Where I group the two.

vm.category_name_image.push(seleted);
// where i want to place the both.

应该是

//it would be better to assign name and picture to properties of the object
var selected = {
    name: vm.data.name, 
    picture: vm.data.picture
}; // Where I group the two.

//you had a typo here --- it should be selected not seleted
vm.category_name_image.push(selected);
// where i want to place the both.

答案 3 :(得分:1)

// where i loop         
vm.data.name = value.name;
vm.data.picture = value.image;
var selected = {
    vm.data.name,
    vm.data.picture
} // Where I group the two.

vm.category_name_image.push(seleted);
// where i want to place the both.
}

您可以使用以下代码

vm.category_name_image.push({name:value.name, picture:value.image});