我有一个从API获取的对象数组,其中一个对象具有“selected”属性。我需要将该数组切片为只有3个对象,其中1个对象需要是“选定”对象。我在一个有角度的应用程序中使用lodash,但我并不限制如何实现这一点,尽管我更喜欢使用lodash的答案。提前致谢...见下面的例子:
//Sample array
var fruits = [{
id: 1,
fruit: "apple",
selected: false
}, {
id: 2,
fruit: "pear",
selected: false
}, {
id: 3,
fruit: "orange",
selected: false
}, {
id: 4,
fruit: "pineaple",
selected: false
}, {
id: 5,
fruit: "mango",
selected: true
}, {
id: 6,
fruit: "peach",
selected: false
}, {
id: 7,
fruit: "strawberry",
selected: false
}];
预期结果:
var fruits = [{
id: 1,
fruit: "apple",
selected: false
}, {
id: 2,
fruit: "pear",
selected: false
}, {
id: 5,
fruit: "mango",
selected: true
}];
答案 0 :(得分:1)
在这里做出3个假设,但是:
var sliced = fruits.slice(0,3);
for (var i=3; i<fruits.length; i+=1)
if (fruits[i].selected)
sliced[0] = fruits[i];
答案 1 :(得分:0)
永远不要理解IE8下划线或lodash的吸引力。现代JS中提供了许多极好的便利方法。有关原生JS数组方法的更多信息,请访问:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
//Sample array
var fruits = [{
fruit: "apple",
selected: false
}, {
fruit: "pear",
selected: false
}, {
fruit: "orange",
selected: false
}, {
fruit: "pineaple",
selected: false
}, {
fruit: "mango",
selected: true
}, {
fruit: "peach",
selected: false
}, {
fruit: "strawberry",
selected: false
}];
function fruitCheck(obj){
var isDesiredFruit = (obj.fruit === 'mango') ||
(obj.fruit === 'peach') ||
(obj.fruit === 'strawberry');
return isDesiredFruit;
}
var filteredFruits = fruits.filter(fruitCheck);
答案 2 :(得分:0)
试一试:
function getThreeFruits (fruits) {
var split = _.partition(fruits, { selected: true })
var selectedFruit = split[0]
var twoOtherFruits = split[1].slice(0, 2)
return selectedFruit.concat(twoOtherFruits)
}
答案 3 :(得分:0)
有很多方法可以解决这个问题!这是另一个Vanilla Javascript版本,可根据您的实际规格随意混合搭配。
var fruits = [{
fruit: "apple",
selected: false
}, {
fruit: "pear",
selected: false
}, {
fruit: "orange",
selected: false
}, {
fruit: "pineaple",
selected: false
}, {
fruit: "mango",
selected: true
}, {
fruit: "peach",
selected: false
}, {
fruit: "strawberry",
selected: false
}];
var selectedFruits = fruits.reduce((result, el) => {
if(el.selected) {
return Array(el).concat(result).slice(0, 3);
}
if (result.length > 2) return result;
result.push(el);
return result;
}, Array());
console.log(selectedFruits);
答案 4 :(得分:0)
var z= _.sortBy(fruits,function(obj){return obj.selected})
var result.push(z.slice(0,2));
result.push(z[z.length-1]);
答案 5 :(得分:0)
在回顾完所有答案后,我决定使用这样的东西。
return user.userStoreAccesses
.reduce(function(arr, el) {
//check if current obj is the defaultStore
if (el.defaultStore) {
return [el].concat(arr).slice(0, 3);
}
//the moment the array is greater than 2 stop execution
if (arr.length > 2) {
return arr;
}
//keep pushing items to the array until...
arr.push(el);
return arr;
}, []);
&#13;
然而,我决定通过链接一些lodash方法(这是我的初衷)比这更简单。这是最终结果:
return _(user.userStoreAccesses)
.chain()
.sortBy("defaultStore")
.reverse()
.slice(0, 3)
.value();
&#13;
感谢您的回答,他们非常有帮助! 我希望我的方法对其他人也有用:)