[英]Finding value of javascript object in an array
Hi really new to javascript and am hoping to get some help with a problem im facing. 嗨,您真是JavaScript新手,希望获得一些有关即时通讯问题的帮助。
So I basically have an array that stores objects. 所以我基本上有一个存储对象的数组。 Each object contains an id and a variable i which is a number.
每个对象都包含一个id和一个变量i,它是一个数字。 My question is this: how can I extract the value of i from the object array with the id value?
我的问题是:如何从具有id值的对象数组中提取i的值? The id that I am using would already have been stored in the array with an i value.
我正在使用的id已经使用i值存储在数组中。
var i = 1;
var id;
var b = {};
var y = [];
if(condition) {
b = {"123":i};
y.push(b);
}
if(condition) {
id = 123;
//Find corresponding i value for id "123" from object array y
i = ?;
}
An example with Array#find Array#find的示例
var hasOwn = Function.prototype.call.bind(Object.prototype.hasOwnProperty); var i = 1; var id; var b = {}; var y = []; var condition = true; if (condition) { b = { "123": i }; y.push(b); } if (condition) { id = 123; // Find corresponding i value for id "123" from object array y // i = ? ; var found = y.find(function(o) { return hasOwn(o, id); }); var f = found ? found[id] : found; console.log(f); }
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.5.9/es5-shim.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.5.9/es5-sham.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/json3/3.3.2/json3.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.35.3/es6-shim.js"></script> <script type="text/javascript" src="https://wzrd.in/standalone/es7-shim@latest"></script>
只需使用ObjectName[Key]
就足以为您获取值,例如b[123]
Many ways to do this. 有很多方法可以做到这一点。 Here is one of them.
这是其中之一。
var arr = [{id:1},{id:123}]; var obj = arr.filter(function(val){ if(val.id===123) return val }) console.log(obj,'obj')
You can loop through the array and get the object property value as follows: 您可以遍历数组并获取对象属性值,如下所示:
var arr = [ {"123": "valueA"}, {"456": "valueB"} ]; const id = "123"; let value; arr.some(obj => { if (obj[id] || obj[id] === 0) value = obj[id]; }); console.log(value);
const stuff = [
{
name: 'Leonardo',
id: 100
},
{
name: 'Donatello',
id: 101
},
{
name: 'Raphael',
id: 102
},
{
name: 'Michaelangelo',
id: 103
},
];
First, use the Array.prototype.find()
method on the array to find the object within it that has the desired ID and store it in the entry
variable. 首先,在数组上使用
Array.prototype.find()
方法在其中查找具有所需ID的对象并将其存储在entry
变量中。 Then, log the value corresponding to the name
key within that object. 然后,记录与该对象内的
name
键相对应的值。
const desired = 102;
const entry = stuff.find(item => item.id === desired);
console.log(entry.name);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.