[英]How to pop and unshift elements from an array in object?
我有一个对象。 我有一个场景,我想用它做什么。
场景:所有数组和功能都添加到 objeTest 中。 之后我会调用它,我想从默认索引中删除 'Wednesday' 值。 我想从第一个索引开始按顺序放置所有“星期三”。
*出现以下错误:
未捕获的类型错误:无法读取未定义的属性“day”*
以下是我的问题的示例。 您可以尝试并从控制台看到错误消息。
我没有找到任何解决方案,我需要您的建议和解决方案。
代码 :
var objeTest = {
name : 'objeTest',
langs : {
0 : 'EN',
1 : 'VI',
2 : 'RU',
3 : 'AR'
},
commentGeneral : 'testComment'
};
var date = [{
day : 'Sunday',
month : 'July',
comment : ''
},
{
day : 'Wednesday',
month : 'June',
comment : 'lorem ipsum dolor sit amet consectetur adipiscing elit'
},
{
day : 'Wednesday',
month : 'June',
comment : 'lorem ipsum dolor sit amet consectetur adipiscing elit'
},
{
day : 'Friday',
month : 'February',
comment : 'lorem ipsum dolor sit amet consectetur adipiscing elit'
}];
/**
* I don't want to remove that using the array adding
* in the object process ( objeTest.dates = date.filter(...)etc).
*/
objeTest.dates = date; // You couldn't change from adding process. I don't need this solution from here.
// If you couldn't understand, please read again scenario. Thanks for your interesting.
var myObjLeng = objeTest.dates.length;
console.log(objeTest);
for(var i = 0; i < myObjLeng; i++) {
if(objeTest.dates[i].day == 'Wednesday') {
objeTest.dates[i].pop();
objeTest.dates[i].unshift();
}
};
console.log(objeTest);
所以我想获取的对象的新日期在对象中应该是这样的:
[
{
day : 'Wednesday',
month : 'June',
comment : 'lorem ipsum dolor sit amet consectetur adipiscing elit'
},
{
day : 'Wednesday',
month : 'August',
comment : 'lorem ipsum dolor sit amet consectetur adipiscing elit'
},
{
day : 'Sunday',
month : 'July',
comment : ''
},
{
day : 'Friday',
month : 'February',
comment : 'lorem ipsum dolor sit amet consectetur adipiscing elit'
}];
尝试排序。
objeTest.dates.sort((entryA, entryB) => {
return (entryB.day === 'Wednesday') - (entryA.day === 'Wednesday')
});
您可以使用排序,请阅读:来自 w3schools 的 Js Array Sort
示例代码:
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b}); // Output: 1,5,10,25,40,100
points.sort(function(a, b){return b - a}); // Output: 100,40,25,10,5,1
如果需要分离数组,最简单的方法是忘记原来的数组,然后重新设置。
not_wednesdays = [];
wednesdays = [];
objeTest.dates.forEach(date=>{
if (date.day=="Wednesday") {
wednesdays.push(date);
}
else {
not_wednesdays.push(date);
}
});
objeTest.dates = not_wednesdays;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.