使用JavaScript计算JSON中的元素

时间:2016-07-23 14:55:54

标签: javascript json

我希望有人可以指出我正确的方向,我已经花了几个小时试图解决我认为是一个简单的问题 - 我已经搜索过并尝试了各种接近但没有雪茄的东西。

我想从下面的示例JSON块中计算两件事。

首先,我想计算productLine条目的数量,然后我想计算类型的数量 - 按产品线计算所有productLine的总数。

所以我想最终得到3个变量,并为它们分配一个数字来表示这三个值。

有人能帮忙吗?

var products = {
  "product": "Product Name",
  "productLines": [{
    "productLine": "Line 1",
    "types": ["Type 1", "Type 2", "Type 3", "Type 4"]
  }, {
    "productLine": "Line 2",
    "types": ["Type 5", "Type 6", "Type 7", "Type 8"]
  }, {
    "productLine": "Line 3",
    "types": ["Type 9", "Type 10", "Type 11"]
  }, {
    "productLine": "Line 4",
    "types": ["Type 12", "Type 13"]
  }]
};

输出类似于:

var productLineCount = 4
var productLine[0].name = "Line 1"
var productLine[0].types.count() = 4
var typesCount = 13

5 个答案:

答案 0 :(得分:1)

你可以通过,

来做到
# Virtual Hosts
#
# Required modules: mod_log_config

# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at 
# <URL:http://httpd.apache.org/docs/2.4/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.

#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ServerName or ServerAlias in any <VirtualHost> block.
#
<VirtualHost *:80>
    ServerAdmin admin@apecenergy
    DocumentRoot /var/www/html/apecenergy.co.uk/public_html
    ServerName www.apecenergy.co.uk
    ServerAlias apecenergy.co.uk 
    ErrorLog "/var/log/httpd/apecenergy-error_log"
    CustomLog "/var/log/httpd/apecenergy-access_log" common
</VirtualHost>

<VirtualHost *:80>
    ServerAdmin admin@apecenergy
    DocumentRoot /var/www/html/plumbing_sites/crouchendplumber.co.uk/public_html
    ServerName www.crouchendplumber.co.uk
    ServerAlias crouchendplumber.co.uk 
</VirtualHost>

第一个是显而易见的,即读取数组的长度。但第二个可以使用winpcap完成。它可以通过多种方式完成。但我建议你在这种背景下使用reduce。

答案 1 :(得分:1)

您可以使用forEach循环并将结果返回到一个对象

&#13;
&#13;
var products = {
  "product": "Product Name",
  "productLines": [{
    "productLine": "Line 1",
    "types": ["Type 1", "Type 2", "Type 3", "Type 4"]
  }, {
    "productLine": "Line 2",
    "types": ["Type 5", "Type 6", "Type 7", "Type 8"]
  }, {
    "productLine": "Line 3",
    "types": ["Type 9", "Type 10", "Type 11"]
  }, {
    "productLine": "Line 4",
    "types": ["Type 12", "Type 13"]
  }]
};

var result = {}
products.productLines.forEach(function(e) {
  result.totalLines = (result.totalLines || 0) + 1;
  e.types.forEach(function(a) {
    result.totalTypes = (result.totalTypes || 0) + 1;
    result[e.productLine + 'Types'] = (result[e.productLine + 'Types'] || 0) + 1;
  });
});

document.body.innerHTML = '<pre>' + JSON.stringify(result, 0, 4) + '</pre>';
&#13;
&#13;
&#13;

答案 2 :(得分:1)

您可以使用自定义API

getter(index, type)

index是产品索引,类型可以是typeCountname

var products = {
  "product": "Product Name",
  "productLines": [{
    "productLine": "Line 1",
    "types": ["Type 1", "Type 2", "Type 3", "Type 4"]
  }, {
    "productLine": "Line 2",
    "types": ["Type 5", "Type 6", "Type 7", "Type 8"]
  }, {
    "productLine": "Line 3",
    "types": ["Type 9", "Type 10", "Type 11"]
  }, {
    "productLine": "Line 4",
    "types": ["Type 12", "Type 13"]
  }]
};

var count = 0;
for (var i = 0, len =  products.productLines.length; i < len; i += 1) {
  count += products.productLines[i].types.length;
}
console.log('productLineCount: ',len);
console.log('typesCount: ', count);

function getter(index, type) {
  var res,
      arr = products.productLines[index];
  if (type === 'name') {
      res = arr.productLine;
  }
  else if (type === 'typeCount') {
    res = arr.types.length;
  }
  return res;
}


console.log('productLine[0].name: ', getter(0, 'name'));
console.log('productLine[0].types.count(): ', getter(0, 'typeCount'));
/*console.log('productLine[1].name: ', getter(1, 'name'));
console.log('productLine[1].types.count(): ', getter(1, 'typeCount'));
console.log('productLine[2].name: ', getter(2, 'name'));
console.log('productLine[2].types.count(): ', getter(2, 'typeCount'));*/

答案 3 :(得分:0)

您可以按如下方式获得三项计数:

var products = {
  "product": "Product Name",
  "productLines": [{
    "productLine": "Line 1",
    "types": ["Type 1", "Type 2", "Type 3", "Type 4"]
  }, {
    "productLine": "Line 2",
    "types": ["Type 5", "Type 6", "Type 7", "Type 8"]
  }, {
    "productLine": "Line 3",
    "types": ["Type 9", "Type 10", "Type 11"]
  }, {
    "productLine": "Line 4",
    "types": ["Type 12", "Type 13"]
  }]
};

var productLineCount = products.productLines.length;
var productTypesCount = products.productLines.map(line => line.types.length);
var totalTypesCount = productTypesCount.reduce((sum, cur) => sum + cur, 0);

console.log('productLineCount', productLineCount);
console.log('productTypesCount', productTypesCount);
console.log('totalTypesCount', totalTypesCount);

&#13;
&#13;
PROFILE_HOME/config/cells/cell/applications/isclite.ear/deployments/isclite/deployment.xml
&#13;
&#13;
&#13;

答案 4 :(得分:0)

为了计算ProductLines,您可以这样做

number_of_productLines = products.productLines.length

按照productLines计算类型,你可以这样做:

productlines_types_count = [] # List of {'productline': name, 'length': int}
products.productLines.forEach(function(productline){ 
    productlines_types_count.push({'productline': productline.productLine, 'length': productline.types.length})
});

同样修复你的json,最后一个对象有一个&#39;类型&#39;我喜欢&#39;类型&#39;:

var products = 
  {
    "product" : "Product Name",
    "productLines": [
      {
        "productLine" : "Line 1",
        "types": ["Type 1", "Type 2", "Type 3", "Type 4"]
      },
      {
        "productLine": "Line 2",
        "types": ["Type 5", "Type 6", "Type 7", "Type 8"]
      },
      {
        "productLine": "Line 3",
        "types": ["Type 9", "Type 10", "Type 11"]
      },
      {
        "productLine": "Line 4",
        "types": ["Type 12", "Type 13"] #here
      }]
   };