我是Javascript的初学者。我正在使用具有两个JSON数组的Javascript创建项目:
var interfaces = [
{id:'123123-12-31-23',mac:'234',flowid:'1',status:'deployed'},
{id:'456456-12-31-23',mac:'45645',flowid:'2',status:'deployed'},
{id:'123123-12-31-234',mac:'45',flowid:'3',status:'deployed'},
{id:'456456-12-31-234',mac:'89',flowid:'4',status:'deployed'}
];
var reorderedInterfaces = [
{id:'456456-12-31-23',mac:'45645',flowid:'2',status:'deployed'},
{id:'456456-12-31-234',mac:'89',flowid:'4',status:'deployed'},
{id:'123123-12-31-234',mac:'45',flowid:'3',status:'deployed'},
{id:'123123-12-31-23',mac:'234',flowid:'1',status:'deployed'},
];
我需要以下输出:
var finalOutput = {
1:2,
2:4,
3:3,
4:1
}
这是我的代码:
var obj = {}
for(i=0; i<interfaces.length; i++){
console.log()
for(j=0; j<reorderedInterfaces.length; j++){
obj[interfaces[i].flowid] = reorderedInterfaces[j].flowid
break;
}
}
console.log(obj)
这给了我错误的输出
答案 0 :(得分:3)
只需在迭代器i和j具有相同值时分配值。
List
List<MyObject> objList = ...;
objList.forEach(e -> transform(e, e.getUuid()));
return objList;
&#13;
答案 1 :(得分:1)
您只需要一个循环并使用相同的索引。
var interfaces = [{ id: '123123-12-31-23', mac: '234', flowid: '1', status: 'deployed' }, { id: '456456-12-31-23', mac: '45645', flowid: '2', status: 'deployed' }, { id: '123123-12-31-234', mac: '45', flowid: '3', status: 'deployed' }, { id: '456456-12-31-234', mac: '89', flowid: '4', status: 'deployed' }],
reorderedInterfaces = [{ id: '456456-12-31-23', mac: '45645', flowid: '2', status: 'deployed' }, { id: '456456-12-31-234', mac: '89', flowid: '4', status: 'deployed' }, { id: '123123-12-31-234', mac: '45', flowid: '3', status: 'deployed' }, { id: '123123-12-31-23', mac: '234', flowid: '1', status: 'deployed' }, ],
result = {};
interfaces.forEach(function (a, i) {
result[a.flowid] = reorderedInterfaces[i].flowid;
});
console.log(result);
答案 2 :(得分:0)
从
更改您的代码var obj = {}
for(i=0; i<interfaces.length; i++){
for(j=0; j<reorderedInterfaces.length; j++){
if(i==j){
obj[interfaces[i].flowid] = reorderedInterfaces[j].flowid;
}
}
}
到
@ResponseBody
表示预期输出。 希望这可以帮助你