简体   繁体   English

如何从数组中获取最后n个元素

[英]How to get last n number of elements from an array an element of that array

I'm working with angular4 and I've been having a lot of trouble trying to display some elements of an array in my view. 我正在使用angular4,尝试在视图中显示数组的某些元素时遇到了很多麻烦。 I got this 我懂了 在此处输入图片说明

the number of elements can change according to the current month so if it was February it would be only M01 and M02 in the array. 元素的数量可以根据当前月份更改,因此如果是2月,则数组中的元素将仅为M01和M02。 I've been trying to loop it in for loop but I can't seem to get it right. 我一直在尝试在for循环中循环播放,但似乎无法正确执行。 any ideas on how to do it? 关于如何做的任何想法?

I'd like to get something like this, all values that start with "M" in a single property 我想得到这样的东西,在单个属性中所有以“ M”开头的值

[0:  M: [...]
     cod_item:...
     cod_condominio:...
...
]

it doesn't matter if it is an array or object as long as i can loop that element to show it in my view. 只要是可以循环显示该元素的数组就可以,无论它是数组还是对象。

You can use nested loops to check is the current property begins with "M" , set the properties, values to a an object, push the object to an array 您可以使用嵌套循环来检查当前属性是否以"M"开头,将属性,值设置为对象,将对象推入数组

 const arr = [{M01:1, M02:2, M03:3, A:4, B:5}, {M04:6, M05:7}]; let res = []; let match = "M"; for (let o of Object.values(arr)) { const curr = {}; for (let [key, prop, [k] = key] of Object.entries(o)) { if (k === match) { curr[key] = prop; } } res.push(curr); } console.log(res); 

If you want just the properties starting with "M", you can use reduce to loop over all the objects and collect just those elements: 如果只需要以“ M”开头的属性,则可以使用reduce循环遍历所有对象并仅收集那些元素:

 // data var arr = [{}, { M0:'foo', M1:'bar', M2:'fum', blah:'blah' }, { M0:'foo', blah:'blah', gee:'gee' } ]; // Build an array of objects only containing // properties starting with "M" followed by digits var result = arr.reduce(function(acc, obj) { var o = {}; // Loop over object keys Object.keys(obj).forEach(function(key){ // Collect those matching the required pattern if (/^M\\d+$/.test(key)) { o[key] = obj[key]; } }); // If found some properties, push into accumulator if (Object.keys(o).length) acc.push(o); return acc; }, []); // Show results console.log(result) // Concise var r = arr.reduce((acc, obj) => { var o = {}; Object.keys(obj).forEach(key => { if (/^M\\d+$/.test(key)) o[key] = obj[key]; }); if (Object.keys(o).length) acc.push(o); return acc; }, []); console.log(r) 

This below solution is rookie way of doing it. 下面的解决方案是新手实现的方法。 But it would be technical debt. 但这将是技术债务。

The below snippet will give you array of elements based on current month. 下面的代码段将根据当前月份为您提供一系列元素。

 var d = new Date(); var n = d.getMonth(); a =[] for(i=1;i<=n;i++){ a.push('M'+('0'+(i).toString()).slice(-2)) } console.log(a) 

in angular template while looping over the object check if the key exist in the array 在角度模板中,同时遍历对象检查键是否存在于数组中

If you have access to backend, the best option is to change the response from your backend, it's not a good idea to refactor the response in front-end. 如果您有权访问后端,最好的选择是从后端更改响应,在前端重构响应不是一个好主意。 So if you have access just change the response to get your needed items in a separated list. 因此,如果您有权访问,只需更改响应即可在单独的列表中获取所需的项目。

But if you using a third party and have no access to backend code, you can use something like this to get only values of items which start with "M" : 但是,如果您使用第三方并且无权访问后端代码,则可以使用类似这样的方法来仅获取以“ M”开头的项目的值:

var a = [
 {
   "M01": 1,
   "M02": 2,
   "code": 44
 },
 {
   "M01": 13,
   "M02": 4,
   "code": 3
 },{
   "M01": 4,
   "M02": 21,
   "code": 11
 }
]

 var t = [];

 for(var i in a){
    for(var j in a[i]){
         if (j[0]=="M") t.push(a[i][j])
     }  
 console.log(t);// it will only have values of items which start with "M"
}

https://jsfiddle.net/f772o781/1/ https://jsfiddle.net/f772o781/1/

 const matchStr = (str) => { const matchArr = str.match(/^M(\\d\\d)/i); if (matchArr) return +matchArr[1]; return 0; } const extractor = (month) => (dataArr) => { return dataArr.map((data) => { const tempObj = {}; const keys = Object.keys(data); keys.forEach((key) => { if (matchStr(key) && matchStr(key) > month) return; tempObj[key] = data[key]; }); return tempObj }); } const yourData = [{ M01: '35238', M02: '123121', M03: '132222', cod_item: '1', filtro: 'saldo' }, { M01: '35238', M02: '123121', M03: '132222', cod_item: '1', filtro: 'saldo' }, { M01: '35238', M02: '123121', M03: '132222', cod_item: '1', filtro: 'saldo' } ]; console.log(extractor(2)(yourData)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM