如何在json中计算类似的值对象?

时间:2016-09-04 13:27:21

标签: javascript arrays json

我有这个JSON结构:

[{
    "name": "ankit",
    "DOB": "23/06"
}, {
    "name": "kapil",
    "DOB": "26/06"
}, {
    "name": "ankit",
    "DOB": "27/06"
}]

我想用值ankit来计算类似的对象。我怎样才能做到这一点?

5 个答案:

答案 0 :(得分:3)

您可以使用Array.prototype.filter()

 [Fact]
 // Arrange
     ...
 // Act
     ... // the AccountController is not available yet
 var accountController
     = new AccountController(userManager: ...,
              signInManager: ...,
                emailSender: null,
                smsSender: null,
                loggerFactory: loggerFactory); // can NOT be null
.............

答案 1 :(得分:1)

怎么样:

let a = [
    { "name": "ankit", "DOB": "23/06" }, 
    { "name": "kapil", "DOB": "26/06" }, 
    { "name": "ankit", "DOB": "27/06" }
];

let count = 0;
a.forEach(item => {
    if (item.name === "ankit") {
        count++;
    }
});

code in playground

答案 2 :(得分:1)

您可以使用reduce方法将名称为ankit的项目缩减为数字。

var items = [
  {
    name: 'ankit',
    DOB: '23/06'
  },
  {
    name: 'kapil',
    DOB: '26/06'
  },
  {
    name: 'ankit',
    DOB: '27/06'
  }
]
    
var numItems = items.reduce(function (count, item) {
  return item.name === 'ankit' ? count + 1 : count
}, 0)

document.write('Number of items with the name `ankit`: ' + numItems)

答案 3 :(得分:1)

您可以使用对象进行计数,并获取名称为property的名称的所需计数。

var data = [{ "name": "ankit", "DOB": "23/06" }, { "name": "kapil", "DOB": "26/06" }, { "name": "ankit", "DOB": "27/06" }],
    count = {};

data.forEach(function (a) {
    count[a.name] = (count[a.name] || 0) + 1;
});

console.log(count);
console.log(count['ankit']);

答案 4 :(得分:0)

<强> 1。从// Product categories $cats = get_the_terms( $post->ID, 'product_cat' ); foreach($cats as $cat) $cats_arr[] = $cat->name; if ( count($cats_arr) > 1) $cats_str = $cats_arr[0] . ', ' . $cats_arr[1]; // return first 2 terms elseif ( count($cats_arr) == 1) $cats_str = $cats_arr[0]; // return one term else $cats_str = ''; // TV shows categories $tvcats = get_the_terms( $post->ID, 'tvshows_cat' ); foreach($tvcats as $tvcat) $tvcat_arr[] = $tvcat->name; if ( count($tvcat_arr) > 1) $tvcats_str = $tvcat_arr[0] . ', ' . $tvcat_arr[1]; // return first 2 terms elseif ( count($tvcat_arr) == 1) $tvcats_str = $tvcat_arr[0]; // return one term else $tvcats_str = ''; // The Display of 2 categories echo $cats_str . $tvcats_str; 获取对象:

JSON

<强> 2。过滤您的阵列:

var obj = JSON.parse(text);