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')
7 个解决方案
#1
36
Arrays are normally accessed via numeric indexes, so in your example arr[0] == {name:"k1", value:"abc"}
. If you know that the name
property 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
#2
49
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。
#3
18
To answer your exact question you can get the exact behaviour you want by extending the Array prototype with:
为了回答你的问题,你可以通过扩展数组原型得到你想要的确切行为:
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
#4
5
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 find
will 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.
如果数组包含具有相同名称的多个元素,并且您希望它们都使用过滤器,它将返回一个数组。
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
+ map
to 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);
#5
3
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 library in general and the detect method in particular. Using detect you could do something like...
对于数组,请检查下划线。一般的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...
#6
2
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].name
will give you 'k1'
, arr[1].value
will give you 'hi'
.
我对jquery一无所知,因此无法帮助您,但就Javascript而言,您有一个对象数组,因此您只能通过每个数组元素访问名称和值。E。g arr[0],名字会给你k1 arr[1]。价值会给你“嗨”。
Maybe you want to do something like:
也许你想做这样的事情:
var obj = {};
obj.k1 = "abc";
obj.k2 = "hi";
obj.k3 = "oa";
alert ("obj.k2:" + obj.k2);
#7
0
try this
试试这个
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;
}
};
#1
36
Arrays are normally accessed via numeric indexes, so in your example arr[0] == {name:"k1", value:"abc"}
. If you know that the name
property 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
#2
49
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。
#3
18
To answer your exact question you can get the exact behaviour you want by extending the Array prototype with:
为了回答你的问题,你可以通过扩展数组原型得到你想要的确切行为:
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
#4
5
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 find
will 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.
如果数组包含具有相同名称的多个元素,并且您希望它们都使用过滤器,它将返回一个数组。
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
+ map
to 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);
#5
3
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 library in general and the detect method in particular. Using detect you could do something like...
对于数组,请检查下划线。一般的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...
#6
2
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].name
will give you 'k1'
, arr[1].value
will give you 'hi'
.
我对jquery一无所知,因此无法帮助您,但就Javascript而言,您有一个对象数组,因此您只能通过每个数组元素访问名称和值。E。g arr[0],名字会给你k1 arr[1]。价值会给你“嗨”。
Maybe you want to do something like:
也许你想做这样的事情:
var obj = {};
obj.k1 = "abc";
obj.k2 = "hi";
obj.k3 = "oa";
alert ("obj.k2:" + obj.k2);
#7
0
try this
试试这个
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;
}
};