[英]Finding value of javascript object in an array
嗨,您真是JavaScript新手,希望获得一些有关即时通讯问题的帮助。
所以我基本上有一个存储对象的数组。 每个对象都包含一个id和一个变量i,它是一个数字。 我的问题是:如何从具有id值的对象数组中提取i的值? 我正在使用的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 = ?;
}
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]
有很多方法可以做到这一点。 这是其中之一。
var arr = [{id:1},{id:123}]; var obj = arr.filter(function(val){ if(val.id===123) return val }) console.log(obj,'obj')
您可以遍历数组并获取对象属性值,如下所示:
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
},
];
首先,在数组上使用Array.prototype.find()
方法在其中查找具有所需ID的对象并将其存储在entry
变量中。 然后,记录与该对象内的name
键相对应的值。
const desired = 102;
const entry = stuff.find(item => item.id === desired);
console.log(entry.name);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.