Javascript 从名称、值 JSON 数组中获取一项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7075485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:44:37  来源:igfitidea点击:

get one item from an array of name,value JSON

javascriptjqueryjson

提问by Omu

I have this array:

我有这个数组:

var arr = [];
arr.push({name:"k1", value:"abc"});
arr.push({name:"k2", value:"hi"});
arr.push({name:"k3", value:"oa"});

is it possible to do get the value or a specific element by knowing the name ?

是否可以通过知道名称来获取值或特定元素?

something like this:

像这样:

arr['k2'].value

or

或者

arr.get('k1')

采纳答案by nnnnnn

Arrays are normally accessed via numeric indexes, so in your example arr[0] == {name:"k1", value:"abc"}. If you know that the nameproperty of each object will be unique you can store them in an object instead of an array, as follows:

数组通常通过数字索引访问,因此在您的示例中arr[0] == {name:"k1", value:"abc"}. 如果您知道name每个对象的属性都是唯一的,您可以将它们存储在一个对象中而不是数组中,如下所示:

var obj = {};
obj["k1"] = "abc";
obj["k2"] = "hi";
obj["k3"] = "oa";

alert(obj["k2"]); // displays "hi"

If you actually want an array of objects like in your post you can loop through the array and return when you find an element with an object having the property you want:

如果你真的想要一个像你文章中那样的对象数组,你可以遍历数组并在找到一个元素的对象具有你想要的属性时返回:

function findElement(arr, propName, propValue) {
  for (var i=0; i < arr.length; i++)
    if (arr[i][propName] == propValue)
      return arr[i];

  // will return undefined if not found; you could return a default instead
}

// Using the array from the question
var x = findElement(arr, "name", "k2"); // x is {"name":"k2", "value":"hi"}
alert(x["value"]); // displays "hi"

var y = findElement(arr, "name", "k9"); // y is undefined
alert(y["value"]); // error because y is undefined

alert(findElement(arr, "name", "k2")["value"]); // displays "hi";

alert(findElement(arr, "name", "zzz")["value"]); // gives an error because the function returned undefined which won't have a "value" property

回答by Langdon

I know this question is old, but no one has mentioned a native solution yet. If you're not trying to support archaic browsers (which you shouldn't be at this point), you can use array.filter:

我知道这个问题很老,但还没有人提到本机解决方案。如果您不想支持过时的浏览器(此时您不应该支持),则可以使用array.filter

var arr = [];
arr.push({name:"k1", value:"abc"});
arr.push({name:"k2", value:"hi"});
arr.push({name:"k3", value:"oa"});

var found = arr.filter(function(item) { return item.name === 'k1'; });

console.log('found', found[0]);
Check the console.

You can see a list of supported browsers here.

您可以在此处查看支持的浏览器列表

In the future with ES6, you'll be able to use array.find.

将来在 ES6 中,您将能够使用array.find

回答by user2314737

Find one element

找到一个元素

To find the element with a given name in an array you can use find:

要在数组中查找具有给定名称的元素,您可以使用find

arr.find(item=>item.name=="k1");

Note that findwill return just one item (namely the first match):

请注意,find将只返回一个项目(即第一个匹配项):

{
  "name": "k1",
  "value": "abc"
}

Find all elements

查找所有元素

In your original array there's only one item occurrence of each name.

在您的原始数组中,每个名称只有一个项目出现。

If the array contains multiple elements with the same name and you want them all then use filter, which will return an array.

如果数组包含多个具有相同名称的元素,并且您希望它们全部都使用filter,则使用,这将返回一个数组。

var arr = [];
arr.push({name:"k1", value:"abc"});
arr.push({name:"k2", value:"hi"});
arr.push({name:"k3", value:"oa"});
arr.push({name:"k1", value:"def"});

var item;

// find the first occurrence of item with name "k1"
item = arr.find(item=>item.name=="k1");
console.log(item);

// find all occurrences of item with name "k1"
// now item is an array
item = arr.filter(item=>item.name=="k1");
console.log(item);

Find indices

查找索引

Similarly, for indices you can use findIndex(for finding the first match) and filter+ mapto find all indices.

同样,对于索引,您可以使用findIndex(用于查找第一个匹配项)和filter+map来查找所有索引。

var arr = [];
arr.push({name:"k1", value:"abc"});
arr.push({name:"k2", value:"hi"});
arr.push({name:"k3", value:"oa"});
arr.push({name:"k1", value:"def"});

var idx;

// find index of the first occurrence of item with name "k1"
idx = arr.findIndex(item=>item.name == "k1");
console.log(idx, arr[idx].value);

// find indices of all occurrences of item with name "k1"
// now idx is an array
idx = arr.map((item, i) => item.name == "k1" ? i : '').filter(String);
console.log(idx);

回答by mythz

To answer your exact question you can get the exact behaviour you want by extending the Array prototype with:

要回答您的确切问题,您可以通过扩展 Array 原型来获得您想要的确切行为:

Array.prototype.get = function(name) {
    for (var i=0, len=this.length; i<len; i++) {
        if (typeof this[i] != "object") continue;
        if (this[i].name === name) return this[i].value;
    }
};

this will add the get() method to all arrays and let you do what you want, i.e:

这会将 get() 方法添加到所有数组并让您执行所需的操作,即:

arr.get('k1'); //= abc

回答by Rob

You can't do what you're asking natively with an array, but javascript objects are hashes, so you can say...

你不能用数组做你本机要求的事情,但javascript对象是散列,所以你可以说......

var hash = {};
hash['k1'] = 'abc';
...

Then you can retrieve using bracket or dot notation:

然后您可以使用括号或点符号检索:

alert(hash['k1']); // alerts 'abc'
alert(hash.k1); // also alerts 'abc'

For arrays, check the underscore.js libraryin general and the detect methodin particular. Using detect you could do something like...

对于数组,一般检查underscore.js 库,特别是检测方法。使用检测你可以做类似的事情......

_.detect(arr, function(x) { return x.name == 'k1' });

Or more generally

或更一般地

MyCollection = function() {
  this.arr = [];
}

MyCollection.prototype.getByName = function(name) {
  return _.detect(this.arr, function(x) { return x.name == name });
}

MyCollection.prototype.push = function(item) {
  this.arr.push(item);
}

etc...

回答by blankabout

I don't know anything about jquery so can't help you with that, but as far as Javascript is concerned you have an array of objects, so what you will only be able to access the names & values through each array element. E.g arr[0].namewill give you 'k1', arr[1].valuewill give you 'hi'.

我对 jquery 一无所知,因此无法帮助您,但是就 Javascript 而言,您有一个对象数组,因此您只能通过每个数组元素访问名称和值。例如arr[0].name会给你'k1'arr[1].value会给你'hi'

Maybe you want to do something like:

也许你想做这样的事情:

var obj = {};

obj.k1 = "abc";
obj.k2 = "hi";
obj.k3 = "oa";

alert ("obj.k2:" + obj.k2);

回答by Ashish Girdhar

The easiest approach which I have used is

我使用过的最简单的方法是

var found = arr.find(function(element) {
         return element.name === "k1";
 });

//If you print the found :
console.log(found);
=> Object { name: "k1", value: "abc" }

//If you need the value
console.log(found.value)
=> "abc"

The similar approach can be used to find the values from the JSON Array based on any input data from the JSON.

类似的方法可用于根据来自 JSON 的任何输入数据从 JSON 数组中查找值。