简体   繁体   English

检查对象数组key是否为空并拼接

[英]Check if array of objects key is empty and splice it

I have an array of objects, in that there is an empty key with Boolean value, if the Boolean value is false then the array of objects should be spliced.我有一个对象数组,其中有一个带有Boolean值的空键,如果Boolean值为false则应该拼接对象数组。

The below is the array structure:下面是数组结构:

 this.dataTobeDeleted= [{ NotificationID: "2180", Quantity: 1, NotificationName: "453", AlertNumber: "02/19/2020", "": true }, { NotificationID: "2182", Quantity: 1, NotificationName: "453", AlertNumber: "02/19/2020", "": false }, { NotificationID: "2181", Quantity: 1, NotificationName: "453", AlertNumber: "02/19/2020", "": false } ]

In the above array there is an empty string "key" if the key value is false then need to splice the array of objects using index.在上面的数组中有一个空字符串“key”,如果key值为false则需要使用索引拼接对象数组。

Below is the code which I have tried:以下是我尝试过的代码:

 for (var i = 0; i < this.dataTobeDeleted.length; i++) { for (var val in this.dataTobeDeleted[i]) { if (val === "") { this.dataTobeDeleted[i]['isCheckedValue'] = this.dataTobeDeleted[i][""]; // insetring new key for empty key string delete this.dataTobeDeleted[i][""]; // Delete old key if (this.dataTobeDeleted[i].isCheckedValue === false) { this.dataTobeDeleted.splice(i, 1) } } } }

The above code is correct, but I need it in shorter way as the code I tried is in lengthier and when there is too much data it will create a problem.上面的代码是正确的,但我需要更短的方式,因为我尝试的代码较长,并且当数据过多时会产生问题。

I tried using filter also, but I am not getting the empty key to check the boolean value.我也尝试使用过滤器,但我没有得到空键来检查boolean值。

Use an array filter to remove the items you don't want:使用数组过滤器删除您不想要的项目:

this.dataTobeDeleted.filter(x => !!x[''])

DEMO: https://stackblitz.com/edit/router-template-1t2xz7演示: https : //stackblitz.com/edit/router-template-1t2xz7

This will create a new array, keeping only those where the property '' is truthy.这将创建一个新数组,只保留属性''为真的数组。 If you wanted to be stricter, you could use a strict boolean check:如果你想更严格,你可以使用严格的布尔检查:

this.dataTobeDeleted.filter(x => x[''] === true)

If your wanting to do this by mutating the original array using splice.如果您想通过使用 splice 改变原始数组来做到这一点。

Make sure you loop the array backwards, this prevents issues of the loop index going out of sync as you mutate the array.确保向后循环数组,这可以防止在更改数组时循环索引不同步的问题。

Example below..下面的例子..

 const dataTobeDeleted= [{ NotificationID: "2180", Quantity: 1, NotificationName: "453", AlertNumber: "02/19/2020", "": true }, { NotificationID: "2182", Quantity: 1, NotificationName: "453", AlertNumber: "02/19/2020", "": false }, { NotificationID: "2181", Quantity: 1, NotificationName: "453", AlertNumber: "02/19/2020", "": false } ]; for (let ix = dataTobeDeleted.length -1; ix >= 0; ix --) { if (!dataTobeDeleted[ix]['']) dataTobeDeleted.splice(ix, 1); } console.log(dataTobeDeleted);

它对我有用,请尝试一下

var newArr = dataTobeDeleted.filter((val) =>{return val[""] === true});

Quoting from MDN on Object.keys() :MDN 上引用Object.keys()

The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would. Object.keys()方法返回给定对象自己的可枚举属性名称的数组,以与普通循环相同的顺序迭代。

Then you can find the empty key and remove it with the delete method.然后你可以找到空键并使用delete方法将其delete

const deletedData = dataTobeDeleted.map((item, index) => {
    Object.keys(item).map(key => {
        if (!item['']) {
            dataTobeDeleted.splice(index, 1);
        }
    });
});
const isCheckedValue = obj => !!(obj[''])
this.dataToBeDeleted = dataToBeDeleted.filter(isCheckedValue)
console.log(result)

If you want to fix such objects simply use map如果您想修复此类对象,只需使用 map

this.dataToBeDeleted = dataToBeDeleted.map(obj => {
   obj.isCheckedValue = obj['']
   delete obj[''] // mutations, not good :(
})

This is experimental, but you could also dabble with native ES6 iterator (using a generator) instead of looping through the data backwards.这是实验性的,但您也可以尝试使用原生 ES6 迭代器(使用生成器),而不是向后循环数据。

 class ClassicIterator { constructor(list) { this.list = list; this.index = 0; } *[Symbol.iterator]() { while (this.index < this.list.length) { yield this.list[this.index]; this.index++; // Move forward } } remove() { this.list.splice(this.index, 1); this.index--; // Rollback } } class InPlaceFilter { constructor(opts) { this.list = opts.list; this.filterFn = opts.filterFn; } execute() { let it = new ClassicIterator(this.list); for (let item of it) { if (!this.filterFn(item)) { it.remove(); } } return this; } get() { return this.list; } } const data = [ { NotificationID:"2180", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":true }, { NotificationID:"2181", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":false }, { NotificationID:"2182", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":false }, { NotificationID:"2183", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":true } ]; let sameRef = new InPlaceFilter({ list : data, filterFn : (e) => e[''] === false }).execute().get(); console.log('Are the same?:', sameRef === data); // Same list!
 .as-console-wrapper { top: 0; max-height: 100% !important; }

Simplified version:简化版:

 const InPlaceFilter = (opts) => { for (let i = opts.list.length - 1; i >= 0; i--) { if (!opts.filterFn(opts.list[i])) { opts.list.splice(i, 1); } } return opts.list; } const data = [ { NotificationID:"2180", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":true }, { NotificationID:"2181", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":false }, { NotificationID:"2182", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":false }, { NotificationID:"2183", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":true } ]; let otherRef = data.filter(e => e[''] === false); let sameRef = InPlaceFilter({ list : data, filterFn : (e) => e[''] === false }); console.log('Are the same?:', sameRef === data); // Same list! console.log('Are the same?:', sameRef === otherRef); // Not the same list!
 .as-console-wrapper { top: 0; max-height: 100% !important; }

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

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