使用JS获取数组中对象的索引
Get index of an object inside of an array with JS
我正在制作一个js代码,从数组中获取对象。我只是想有一个脚本,采取对象索引,并在html页面上打印它。我尝试了很多不同的方法,但都不起作用。例如,假设第一个{}为0,然后第二个速率为3.3的{}为1…这是一个jsfiddle: https://jsfiddle.net/76e40vqg/1/
var data = [{"image":"link1","name":"Name1","address":"Address1","rate":"4.4"},{"image":"link2","name":"Name2","address":"Address2","rate":"3.3"},{"image":"link3","name":"Name3","address":"Address3","rate":"3.2"}
];
var restoName = [];
for(i = 0; i < data.length; i++){
if(restoName.indexOf(data[i].name) === -1){
restoName.push(data[i].name);
}
}
var restoAddress = [];
for(i = 0; i < data.length; i++){
if(restoAddress.indexOf(data[i].address) === -1){
restoAddress.push(data[i].address);
}
}
var restoRate = [];
for(i = 0; i < data.length; i++){
if(restoRate.indexOf(data[i].rate) === -1){
restoRate.push(data[i].rate);
}
}
var restoImage = [];
for(i = 0; i < data.length; i++){
if(restoImage.indexOf(data[i].image) === -1){
restoImage.push(data[i].image);
}
}
for(i = 0; i < restoName.length; i++){
document.getElementById('output').innerHTML += "Image : <a href='" + restoImage[i] + "'><div class='thumb' style='background-image:" + 'url("' + restoImage[i] + '");' + "'></div></a><br>" + "Name : " + restoName[i] + "<br>" + "Address : " + restoAddress[i] + "<br>" + "Rate : " + restoRate[i] + "<br>" + "Index" + "<br><hr>";
}
谢谢
我想你缺少..."Index" + i +"<br>...
@Nina Scholz的解决方案也起作用了
您可以只使用一个循环来显示Array#forEach
的数据。
forEach()
方法对每个数组元素执行一次提供的函数。
var data = [{ image: "link1", name: "Name1", address: "Address1", rate: "4.4" }, { image: "link2", name: "Name2", address: "Address2", rate: "3.3" }, { image: "link3", name: "Name3", address: "Address3", rate: "3.2" }];
data.forEach(function (object, index){
console.log('index', index);
console.log('image', object.image);
console.log('name', object.name);
console.log('address', object.address);
console.log('rate', object.rate);
console.log('--');
});
传统的for
循环和索引i
。
var data = [{ image: "link1", name: "Name1", address: "Address1", rate: "4.4" }, { image: "link2", name: "Name2", address: "Address2", rate: "3.3" }, { image: "link3", name: "Name3", address: "Address3", rate: "3.2" }],
i;
for (i = 0; i < data.length; i++) {
console.log('index', i);
console.log('image', data[i].image);
console.log('name', data[i].name);
console.log('address', data[i].address);
console.log('rate', data[i].rate);
console.log('--');
}
相关文章:
- 在JavaScript中通过索引从对象数组中获取值
- Javascript:根据对象的嵌套数组中的值,在数组中查找对象的索引
- “未定义的索引:itemdetails”,当将JSON对象从JavaScript发送到PHP时
- 在知道对象值的情况下,确定数组中JS对象的索引
- 索引IndexedDB中对象中的数组值
- 对象中的索引错误
- 按键查找数组中对象的索引
- 使用Handlebars获取同级JSON数据,其中单个对象没有父索引键,但多个项有一个索引键
- AngularJS - ng-repeat,更新尚未定义的模型对象索引
- 来自 jsp 和 javascript 中的请求属性的对象索引数组
- 使用变量作为对象索引
- 如何使用 JavaScript 获取对象索引值的 JSON 响应
- NamedNodeMap对象内部的Attr对象索引问题
- 使用json中的id查找对象索引
- JSON获取对象索引
- 生成对象而不是对象索引的Javascript for循环
- jQuery对象索引忽略jQuery.filter()
- 确定特定字符串的对象索引
- Angularjs访问对象索引
- 按字符串查找对象索引