如果两个值都不存在,我如何推入数组?这是我的数组:
[
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" }
]
如果我试图再次推入数组的名字:“tom”或文本:“tasty”,我不希望发生任何事情…但如果这两个都不存在那么我就输入。push()
我该怎么做呢?
如果不在列表中,则添加
对于一个简单值的列表,它是一行程序…
[...new Set([...someArray, someElement])]
JavaScript的用法:
var myArray = ['bill','bob']
var alreadyIn = [...new Set([...myArray, 'bob'])] // ['bill','bob']
var notAlreadyIn = [...new Set([...myArray, 'peter'])] // ['bill','bob','peter']
TypeScript文本(注意include vs includes):
interface Array<T> {
include(element: T): Array<T>
}
Array.prototype.include = function (element: any): any[] {
return [...new Set([...this, obj])]
}
...但对于对象来说,情况就复杂多了
[...new Set([...someArray.map((o) => JSON.stringify(o)),
JSON.stringify(someElement)]).map((o) => JSON.parse(o))
TypeScript文本处理任何事情:
Array.prototype.include = function (element: any): any[] {
if (element && typeof element === 'object')
return [
...new Set([
...this.map((o) => JSON.stringify(o)),
JSON.stringify(element),
]),
].map((o) => JSON.parse(o))
else return [...new Set([...this, element])]
}
如果你的项目包含lodash,使用unionBy方法会很简单
import {unionBy} from "lodash";
let arrayObj = [
{ name: "jhon", text: "guitar"},
{ name: "paul", text: "bass" },
{ name: "george", text: "guitar" }
];
// this object will be added to the array
arrayObj = unionBy(arrayObj, [{name: 'ringo', text: 'drums'}], 'name')
// this object will be ignored because already exists
arrayObj = unionBy(arrayObj, [{name: "jhon", text: "guitar"}], 'name')