说我有一个数组内的objectA
:[ { name: 'ObjectA'}, { name: 'ObjectB'}, { name: 'ObjectC' } ]
如何找到ObjectA
旁边的对象(例如ObjectB
)?
(我可以使用vanilla JavaScript或Lodash。)
答案 0 :(得分:1)
您可以使用Array.prototype.reduce()
:
var arr = [{
name: 'ObjectA'
}, {
name: 'ObjectB'
}, {
name: 'ObjectC'
}];
var nxt = arr.reduce(function(a, b){
return (a.name === 'ObjectA') ? b : a;
});
document.querySelector('pre').innerHTML = JSON.stringify(nxt, 0 , 4);

<pre></pre>
&#13;
答案 1 :(得分:0)
假设你想要下一个对象,给定当前对象的名称,试试这个。
var getNextObject = function(arr,name){
var currIndex = - 1;
arr.forEach((i,index)=>{
if(i.name === name){
currIndex = index;
};
});
if(currIndex < (arr.length - 1 && currIndex >=0)){
return arr[currIndex+1];
}
//return null if its the last element or the object with such name does not exist in the array
return null;
}
var arr = [ { name: 'ObjectA'}, { name: 'ObjectB'}, { name: 'ObjectC' } ];
//Most of the code from here on is for demonstration purposes
//
// This function call is good enough ==> getNextObject(arr,'ObjectA');
//
var nextOfObjectA = getNextObject(arr,'ObjectA');
var myprea = document.getElementById('newprea');
if(nextOfObjectA && nextOfObjectA.name){
myprea.innerHTML = nextOfObjectA.name;
}else{
myprea.innerHTML = 'does not exist';
}
var nextOfObjectC = getNextObject(arr,'ObjectC');
var myprec = document.getElementById('newprec');
//Object C is the last element, hence the function returns null
if(nextOfObjectC && nextOfObjectC.name){
myprec.innerHTML = nextOfObjectC.name;
}else{
myprec.innerHTML = 'does not exist';
}
<br/>
<p> Next Object for objectA = <span id="newprea"></span> </p>
<br/>
<p> Next Object for objectC = <span id="newprec"></span> </p>
答案 2 :(得分:0)
您可以找到对象的索引(使用findIndex),然后获取下一个项目。
var objArr = [ { name: 'ObjectA'}, { name: 'ObjectB'}, { name: 'ObjectC' } ];
var nextObj = objArr[objArr.findIndex(function(item, index) { return item.name == this;}, 'ObjectA')+1];
alert(JSON.stringify(nextObj));
console.log(nextObj);
答案 3 :(得分:0)
试试这个
var arr = [ { name: 'ObjectA'}, { name: 'ObjectB'}, { name: 'ObjectC' } ];
var objIndex = -1;
arr.forEach( function(value, index){ if ( value.name == "ObjectA" ){ objIndex = index + 1; } } );
console.log( arr[objIndex].name );
答案 4 :(得分:0)
试试这个:
function getNextOrDefault (name){
//Fetch index of item.
var index = _.findIndex(ary,function(item){
return item.name === name;
});
//If item found (!==-1) and has next item (item's index + 1 > length of array)
return (index !== -1 ? index++ : index) > ary.length || index === -1
//Return default
? null
//Return next item
: ary[index] ;
}
JsFiddle:https://jsfiddle.net/k4dgnzpf/
希望这有帮助!