繁体   English   中英

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

[英]Can I put an object and an array together inside another array?

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

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}]

您不能创建没有名称的对象属性:

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

或者如果确实需要仅使用数据(糟糕的方式),则可以使用数组:

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

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
});

您的示例中有错字。

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.
// 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});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM