我有一个对象数组,我想从中获取值:
lastChanceSeats: Object
assignedSeats: Array[6]
0: Object
SeatId: "29A"
passengerName: "Mr test1 test1"
sectorSequence: 1
1: Object
SeatId: "22A"
passengerName: "Mr test1 test1"
sectorSequence: 2
2: Object
SeatId: "29B"
passengerName: "Mrs test2 test2"
sectorSequence: 1
3: Object
SeatId: "22B"
passengerName: "Mrs test2 test2"
sectorSequence: 2
4: Object
SeatId: "29C"
passengerName: "Master test3 test3"
sectorSequence: 1
5: Object
SeatId: "22C"
passengerName: "Master test3 test3"
sectorSequence: 2
我想以下列格式呈现数据:
......然后对于乘客二,三等相同。
答案 0 :(得分:0)
使用简单的模板并遍历每个项目以生成输出:
var data=[
{
"SeatId": "29A",
"passengerName": "Mr test1 test1",
"sectorSequence": 1
},
{
"SeatId": "22A",
"passengerName": "Mr test1 test1",
"sectorSequence": 2
},
{
"SeatId": "29B",
"passengerName": "Mrs test2 test2",
"sectorSequence": 1
}
]
function template(ob, str){
return str.replace(/{([\w\s.\$]+?)}/g,
function(j,a){ return ob[a]||""; } );
}
strTemplate="First {passengerName} {sectorSequence} + {SeatId}";
out=$(data).map(function(i,item){ return template(item, strTemplate)}).toArray().join("\n");
alert(out);
/* result:
First Mr test1 test1 1 + 29A
First Mr test1 test1 2 + 22A
First Mrs test2 test2 1 + 29B */
答案 1 :(得分:0)
无法对对象属性进行有序迭代。
你可以这样做:
var data=[
{
"SeatId": "29A",
"passengerName": "Mr test1 test1",
"sectorSequence": 1
},
{
"SeatId": "22A",
"passengerName": "Mr test1 test1",
"sectorSequence": 2
},
{
"SeatId": "29B",
"passengerName": "Mrs test2 test2",
"sectorSequence": 1
}
],
orderedObjectProps = ['SeatId', 'passengerName', 'sectorSequence'],
dataLength = data.length,
propsLength = orderedObjectProps.length,
i = 0;
for(i; i < dataLength; i++) {
var obj = data[i],
j = 0;
for(j; j < propsLength; j++) {
var propName = orderedObjectProps[j],
propValue = obj[propName];
console.log(propValue);
}
}
上面的代码将按您想要的顺序打印值。
答案 2 :(得分:0)
使用与上述答案相同的数据,您可以尝试以下代码段
var data=[
{
"SeatId": "29A",
"passengerName": "Mr test1 test1",
"sectorSequence": 1
},
{
"SeatId": "22A",
"passengerName": "Mr test1 test1",
"sectorSequence": 2
},
{
"SeatId": "29B",
"passengerName": "Mrs test2 test2",
"sectorSequence": 1
}
]
function test_iteration(data) {
data.forEach(e => {
console.log(`SeatId : ${e.SeatId}`);
console.log(`passengerName : ${e.passengerName}`);
console.log(`sectorSequence : ${e.sectorSequence}`);
})
}
function test_iteration_2(data) {
data.forEach(e => {
for (var prop in e) {
if (Object.prototype.hasOwnProperty.call(e, prop)) {
console.log(`${prop} : ${e[prop]}`);
}
}
})
}
test_iteration_2(data) ;