在JavaScript中循环对象的属性?

时间:2022-08-30 10:14:33

I have the set of data.how would you loop through this data using a for loop in JavaScript?

我有一组数据。你会在JavaScript中使用for循环遍历这些数据吗?

    var model = ({
        "DettolRadiance":
            {
                "Values": [{ "GRPsValue": 66, "MonthOfSale": "Jan" },
                  { "GRPsValue": 100, "MonthOfSale": "Feb" },
                  { "GRPsValue": 250, "MonthOfSale": "March" },
                  { "GRPsValue": 100, "MonthOfSale": "April" }],
                "Key": "DettolRadiance"
            },
        "DettolSkinCare":
            {
                 "Values": [{ "GRPsValue": 487, "MonthOfSale": "Jan" },
                        { "GRPsValue": 450, "MonthOfSale": "Feb" },
                        { "GRPsValue": 300, "MonthOfSale": "March" },
                        { "GRPsValue": 400, "MonthOfSale": "April" }],
                 "Key": "DettolSkinCare"
            },
        "DettolToiletSoaps":
                    {
                 "Values": [{ "GRPsValue": 64, "MonthOfSale": "Feb" },
                            { "GRPsValue": 0,  "MonthOfSale": "Jan" },
                            { "GRPsValue": 70, "MonthOfSale": "March" },
                            { "GRPsValue": 150, "MonthOfSale": "April" }],
                 "Key": "DettolToiletSoaps"
             }
    });

Here is the code which I have tried.

这是我尝试过的代码。

      var DataSet = [];

           for (var i = 0; i < model[0].DettolRadiance.Values.length; i++) {

            DataSet.push({ 'x': model[0].DettolRadiance.Values[i].MonthOfSale, 'y': model[0].DettolRadiance.Values[i].GRPsValue });

        }

            for (var i = 0; i < model[0].DettolSkinCare.Values.length; i++) {

            DataSet.push({ 'x': model[0].DettolSkinCare.Values[i].MonthOfSale, 'y': model[0].DettolSkinCare.Values[i].GRPsValue });
        }


             for (var i = 0; i < model[0].DettolToiletSoaps.Values.length; i++) {

            DataSet.push({ 'x': model[0].DettolToiletSoaps.Values[i].MonthOfSale, 'y': model[0].DettolToiletSoaps.Values[i].GRPsValue });
        }

But I am able to retrieve only Values.I want to retrieve values based on 3 keys.Those are DettolRadiance,DettolSkinCare,DettolToiletSoaps.So Each key should have 4 respective values.I think I need to add another for loop.But I am not getting the exact syntax.Can anyone please help..

但我只能检索Values.I想要检索基于3个键的值。这些是DettolRadiance,DettolSkinCare,DettolToiletSoaps.So每个键应该有4个相应的值。我想我需要添加另一个for循环。但我不是得到确切的语法。任何人都可以帮助..

3 个解决方案

#1


0  

i think you code should be

我认为你的代码应该是

  var model = ({
        "DettolRadiance":
            {
                "Values": [{ "GRPsValue": 66, "MonthOfSale": "Jan" },
                  { "GRPsValue": 100, "MonthOfSale": "Feb" },
                  { "GRPsValue": 250, "MonthOfSale": "March" },
                  { "GRPsValue": 100, "MonthOfSale": "April" }],
                "Key": "DettolRadiance"
            },
        "DettolSkinCare":
            {
                 "Values": [{ "GRPsValue": 487, "MonthOfSale": "Jan" },
                        { "GRPsValue": 450, "MonthOfSale": "Feb" },
                        { "GRPsValue": 300, "MonthOfSale": "March" },
                        { "GRPsValue": 400, "MonthOfSale": "April" }],
                 "Key": "DettolSkinCare"
            },
        "DettolToiletSoaps":
                    {
                 "Values": [{ "GRPsValue": 64, "MonthOfSale": "Feb" },
                            { "GRPsValue": 0,  "MonthOfSale": "Jan" },
                            { "GRPsValue": 70, "MonthOfSale": "March" },
                            { "GRPsValue": 150, "MonthOfSale": "April" }],
                 "Key": "DettolToiletSoaps"
             }
    });

var DataSet = [];

           for (var i = 0; i < model.DettolRadiance.Values.length; i++) {
            DataSet.push({ 'x': model.DettolRadiance.Values[i].MonthOfSale, 'y': model.DettolRadiance.Values[i].GRPsValue });

        }

            for (var i = 0; i < model.DettolSkinCare.Values.length; i++) {

            DataSet.push({ 'x': model.DettolSkinCare.Values[i].MonthOfSale, 'y': model.DettolSkinCare.Values[i].GRPsValue });
        }


             for (var i = 0; i < model.DettolToiletSoaps.Values.length; i++) {

            DataSet.push({ 'x': model.DettolToiletSoaps.Values[i].MonthOfSale, 'y': model.DettolToiletSoaps.Values[i].GRPsValue });
        }

#2


-1  

I have written two functions which allow you to iterate over every individual member of an array/object or a combination of object and array (like yours).

我编写了两个函数,允许您迭代数组/对象的每个单独成员或对象和数组的组合(如您的)。

First I have written a function to iterate over every individual member of an array/object. But this function also uses another function to check whether the object is object object or is object array, since we should slightly use different techniques for the two types.

首先,我编写了一个函数来迭代数组/对象的每个成员。但是这个函数还使用另一个函数来检查对象是对象对象还是对象数组,因为我们应该对这两种类型略微使用不同的技术。

function _recursive(obj, callback)
{
  var len;
  var objectKeys;
  var i  = 0;
  if(isArrayOrObject(obj) === 'array') 
  {
     len = obj.length; 
     iterator = i;
  }
  else if(isArrayOrObject(obj) === 'object') 
  {
     len = Object.keys(obj).length;

     objectKeys = Object.keys(obj);
  }

   for(i = 0; i < len; i++)
   {
       var currentElement;

       if(isArrayOrObject(obj) === 'array') 
       {
         currentElement = obj[i];
       }
       else if(isArrayOrObject(obj) === 'object') 
       {
         currentElement = obj[objectKeys[i]];
       }

       callback(currentElement);

       if(isArrayOrObject(currentElement) !== false)
       {         
             _recursive(currentElement, function(element){
                    callback(element);
              }); 
           }
       }
    }

This function checks the type of the object and returns false if neither are true.

此函数检查对象的类型,如果两者都不为则返回false。

function isArrayOrObject(inp)
{ 
  if(typeof inp !== 'object') return false;  
  if( Object.prototype.toString.call( inp ) === '[object Array]' ) 
    {
        return "array";
    } 
    else 
    {
      return "object"; 
    }

}

And here is how we call it. We pass a callback to our function to be applied to each individual member of the array.

这就是我们称之为的方式。我们将回调传递给我们的函数,以应用于数组的每个成员。

_recursive(model, function(element){

    if(typeof element !== 'object')
    {
        console.log(element); 
    }
});

This loops through the object to the deepest root.

这会将对象循环到最深的根。

#3


-1  

You can loop through object properities with for..in.

您可以使用for..in循环遍历对象特性。

for (var prop in obj) {
  if( obj.hasOwnProperty( prop ) ) {
    console.log("o." + prop + " = " + obj[prop]);
  } 
}

hasOwnProperty ensures that it is a "real" property and that we don't get tripped up if somebody has been monkying with Object.prototype.

hasOwnProperty确保它是一个“真正的”属性,如果有人一直在使用Object.prototype,我们不会被绊倒。

To get an array with the collected MonthOfSale and GRPsValue of each product you would use for..in with an inner loop on Values.

要获得一个数组,其中包含每个产品的收集的MonthOfSale和GRPsValue,您将使用for..in和值的内部循环。

function proccessData(data){
    var result = [];

    for (var prop in data) {
        if( data.hasOwnProperty( prop ) ) {
            (function(product){
                var val, i, len = product.Values.length;
                for (i = 0; i < len; i++){
                    val = product.Values[i];
                    result.push({
                        x: val['MonthOfSale'],
                        y: val['GRPsValue']
                    });
                }
            }(data[prop]));
        }
    }

    return result;
}

jsFiddle http://jsfiddle.net/maxcal/9uoqm6f8/3/

PS: (added)

When creating a object with literal notation don't wrap it in parens:

使用文字表示法创建对象时,请勿将其包装在parens中:

var model = {}; // good
var model = ({}); // bad, is there something missing here?

Although the result is the same it is confusing since it looks like you may have intended to pass the literal to a function.

虽然结果是相同的,但它很混乱,因为看起来你可能打算将文字传递给函数。

EDIT. This will do the same as your accepted answer.

编辑。这将与您接受的答案相同。

var data_set = [];

for (var prop in model) {
  if( model.hasOwnProperty( prop ) ) {
     data_set.push({ values: model[prop].Values, key: model[prop].Key })
  } 
}

#1


0  

i think you code should be

我认为你的代码应该是

  var model = ({
        "DettolRadiance":
            {
                "Values": [{ "GRPsValue": 66, "MonthOfSale": "Jan" },
                  { "GRPsValue": 100, "MonthOfSale": "Feb" },
                  { "GRPsValue": 250, "MonthOfSale": "March" },
                  { "GRPsValue": 100, "MonthOfSale": "April" }],
                "Key": "DettolRadiance"
            },
        "DettolSkinCare":
            {
                 "Values": [{ "GRPsValue": 487, "MonthOfSale": "Jan" },
                        { "GRPsValue": 450, "MonthOfSale": "Feb" },
                        { "GRPsValue": 300, "MonthOfSale": "March" },
                        { "GRPsValue": 400, "MonthOfSale": "April" }],
                 "Key": "DettolSkinCare"
            },
        "DettolToiletSoaps":
                    {
                 "Values": [{ "GRPsValue": 64, "MonthOfSale": "Feb" },
                            { "GRPsValue": 0,  "MonthOfSale": "Jan" },
                            { "GRPsValue": 70, "MonthOfSale": "March" },
                            { "GRPsValue": 150, "MonthOfSale": "April" }],
                 "Key": "DettolToiletSoaps"
             }
    });

var DataSet = [];

           for (var i = 0; i < model.DettolRadiance.Values.length; i++) {
            DataSet.push({ 'x': model.DettolRadiance.Values[i].MonthOfSale, 'y': model.DettolRadiance.Values[i].GRPsValue });

        }

            for (var i = 0; i < model.DettolSkinCare.Values.length; i++) {

            DataSet.push({ 'x': model.DettolSkinCare.Values[i].MonthOfSale, 'y': model.DettolSkinCare.Values[i].GRPsValue });
        }


             for (var i = 0; i < model.DettolToiletSoaps.Values.length; i++) {

            DataSet.push({ 'x': model.DettolToiletSoaps.Values[i].MonthOfSale, 'y': model.DettolToiletSoaps.Values[i].GRPsValue });
        }

#2


-1  

I have written two functions which allow you to iterate over every individual member of an array/object or a combination of object and array (like yours).

我编写了两个函数,允许您迭代数组/对象的每个单独成员或对象和数组的组合(如您的)。

First I have written a function to iterate over every individual member of an array/object. But this function also uses another function to check whether the object is object object or is object array, since we should slightly use different techniques for the two types.

首先,我编写了一个函数来迭代数组/对象的每个成员。但是这个函数还使用另一个函数来检查对象是对象对象还是对象数组,因为我们应该对这两种类型略微使用不同的技术。

function _recursive(obj, callback)
{
  var len;
  var objectKeys;
  var i  = 0;
  if(isArrayOrObject(obj) === 'array') 
  {
     len = obj.length; 
     iterator = i;
  }
  else if(isArrayOrObject(obj) === 'object') 
  {
     len = Object.keys(obj).length;

     objectKeys = Object.keys(obj);
  }

   for(i = 0; i < len; i++)
   {
       var currentElement;

       if(isArrayOrObject(obj) === 'array') 
       {
         currentElement = obj[i];
       }
       else if(isArrayOrObject(obj) === 'object') 
       {
         currentElement = obj[objectKeys[i]];
       }

       callback(currentElement);

       if(isArrayOrObject(currentElement) !== false)
       {         
             _recursive(currentElement, function(element){
                    callback(element);
              }); 
           }
       }
    }

This function checks the type of the object and returns false if neither are true.

此函数检查对象的类型,如果两者都不为则返回false。

function isArrayOrObject(inp)
{ 
  if(typeof inp !== 'object') return false;  
  if( Object.prototype.toString.call( inp ) === '[object Array]' ) 
    {
        return "array";
    } 
    else 
    {
      return "object"; 
    }

}

And here is how we call it. We pass a callback to our function to be applied to each individual member of the array.

这就是我们称之为的方式。我们将回调传递给我们的函数,以应用于数组的每个成员。

_recursive(model, function(element){

    if(typeof element !== 'object')
    {
        console.log(element); 
    }
});

This loops through the object to the deepest root.

这会将对象循环到最深的根。

#3


-1  

You can loop through object properities with for..in.

您可以使用for..in循环遍历对象特性。

for (var prop in obj) {
  if( obj.hasOwnProperty( prop ) ) {
    console.log("o." + prop + " = " + obj[prop]);
  } 
}

hasOwnProperty ensures that it is a "real" property and that we don't get tripped up if somebody has been monkying with Object.prototype.

hasOwnProperty确保它是一个“真正的”属性,如果有人一直在使用Object.prototype,我们不会被绊倒。

To get an array with the collected MonthOfSale and GRPsValue of each product you would use for..in with an inner loop on Values.

要获得一个数组,其中包含每个产品的收集的MonthOfSale和GRPsValue,您将使用for..in和值的内部循环。

function proccessData(data){
    var result = [];

    for (var prop in data) {
        if( data.hasOwnProperty( prop ) ) {
            (function(product){
                var val, i, len = product.Values.length;
                for (i = 0; i < len; i++){
                    val = product.Values[i];
                    result.push({
                        x: val['MonthOfSale'],
                        y: val['GRPsValue']
                    });
                }
            }(data[prop]));
        }
    }

    return result;
}

jsFiddle http://jsfiddle.net/maxcal/9uoqm6f8/3/

PS: (added)

When creating a object with literal notation don't wrap it in parens:

使用文字表示法创建对象时,请勿将其包装在parens中:

var model = {}; // good
var model = ({}); // bad, is there something missing here?

Although the result is the same it is confusing since it looks like you may have intended to pass the literal to a function.

虽然结果是相同的,但它很混乱,因为看起来你可能打算将文字传递给函数。

EDIT. This will do the same as your accepted answer.

编辑。这将与您接受的答案相同。

var data_set = [];

for (var prop in model) {
  if( model.hasOwnProperty( prop ) ) {
     data_set.push({ values: model[prop].Values, key: model[prop].Key })
  } 
}

相关文章