javascript - Dynamically create angular object with key, value from angular.forEach() - Stack Overflow

if ($scope.data) {$formData = [];angular.forEach($scope.data, function(value, key){console.log(key);

    if ($scope.data) {
        $formData = [];
        angular.forEach($scope.data, function(value, key){

            console.log(key);  //  o/p: 'fruitname'
            var k = key;
            var value = value || 'Not Available';
            console.log(value); // o/p: 'apple'

            var parts = {k : value};
            console.log(parts);  // o/p: Object {k: "apple"}
            $formData.push(parts);
        });
    }

Why i cannot able to populate key, while creating parts object. or how can i do the same.

    if ($scope.data) {
        $formData = [];
        angular.forEach($scope.data, function(value, key){

            console.log(key);  //  o/p: 'fruitname'
            var k = key;
            var value = value || 'Not Available';
            console.log(value); // o/p: 'apple'

            var parts = {k : value};
            console.log(parts);  // o/p: Object {k: "apple"}
            $formData.push(parts);
        });
    }

Why i cannot able to populate key, while creating parts object. or how can i do the same.

Share asked Jul 11, 2015 at 13:32 JyotirmayJyotirmay 1,8553 gold badges25 silver badges43 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

What you need to do is parts[k] = value; Actually when you assign parts = { k : value }; , This goes something like this :

parts["k"] = value;

So you see instead of taking the value of k, it takes k as string and assign a value to this string as key field.

it works when i try to do like this.

if ($scope.data) {
    $formData = [];
    angular.forEach($scope.data, function(value, key){

        console.log(key);  //  o/p: 'fruitname'
        var value = value || 'Not Available';
        console.log(value); // o/p: 'apple'

        var parts = {};
        parts[key] = value;
        console.log(parts);  // o/p: Object {"fruitname": "apple"}
        $formData.push(parts);
    });
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742264800a4411580.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信