如何从JavaScript数组中选择特定字段 [英] How to select a particular field from javascript array

查看:57
本文介绍了如何从JavaScript数组中选择特定字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在javascript中有一个数组对象.我将从对象的所有行中选择一个特定的字段.

I have an array object in javascript. I would to select a particular field from all the rows of the object.

我有一个类似

var sample = {
[Name:"a",Age:1],
[Name:"b",Age:2],
[Name:"c",Age:3]
}

我希望仅将名称输出为["a","b","c"],而无需遍历示例对象.

I would like to get an output of only Names as ["a","b","c"] without looping over sample object.

如何使用jlinq选择一个或两个字段?或其他任何插件?

How can I select one or two fields using jlinq? or any other plugin?

非常感谢.

推荐答案

您的定义是错误的.您需要一个对象数组来代替包含3个数组的对象.

You've got your definition the wrong way round. Instead of having an object containing 3 arrays, you want an array of objects.

像这样:

var sample = [{Name:"a",Age:1},
   {Name:"b",Age:2},
   {Name:"c",Age:3}];

然后您可以执行以下操作:

Then you can do:

var name0 = sample[0].Name;
var age0 = sample[0].Age;

或根据您的示例获取所有名称:

or to get all your names as per your example:

var names = [sample[0].Name,sample[1].Name,sample[2].Name];

但是,如果没有循环,我不确定如何获取任意数量的值....为什么没有循环?

But, without looping im not sure how you would get any number of values.... why no looping?

只需说您要循环,这是您要执行的操作:

Just say you do loop, here's how you would do it:

var names = []
for(x in sample)
   names.push(sample[x].Name);

或使用jQuery(仍在循环中)

or with jQuery (which is still looping)

sample= jQuery.map(sample, function(n, i){
  return n.Name;
});

这篇关于如何从JavaScript数组中选择特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆