我有两个对象数组。在第二个数组中,您可以从第一个数组中分配一个ID。如果第一个数组的ID在array2中未关联,如何过滤第一个数组以仅显示结果?我已经尝试过在lodash中过滤器的嵌套过滤器和find过滤器的嵌套过滤器,但是它不起作用。
这是我尝试过的:
array1.filter(item => item.id === find(array2,{associateID:item.id})[0] .associatedID)在过滤器内部进行查找的第二次迭代。我尝试了类似的过滤器方法而不是查找,但是那也不起作用。如在父过滤器参数中提供的那样,在find函数中使用item.id是否存在问题?还是没有?
帮助?
const array1 = [{
"id": "1",
"name": "Test 1"
},
{
"id": "2",
"name": "Test 2",
}
{
"id": "3",
"name": "Test 3",
}
]
const array2 = [{
"id": "12",
"name": "Test 1",
"associatedID": "1"
},
{
"id": "22",
"name": "Test 2",
"associatedID": "2"
}
{
"id": "32",
"name": "Test 3",
}
]
答案 0 :(得分:2)
效果不佳的方法是
array1.filter(elm1 => {
return array2.find(elm2 => elm2.associatedID === elm1).length === 1
})
如果您的数组很大,则可以根据ID和关联的ID对两个数组进行排序,并对两个数组运行一个for循环以某种方式返回结果
答案 1 :(得分:1)
使用lodash的_.differenceWith()
从array
获取associatedID
中没有array2
的所有项目:
const array1 =[{"id":"1","name":"Test 1"},{"id":"2","name":"Test 2"},{"id":"3","name":"Test 3"}]
const array2 = [{"id":"12","name":"Test 1","associatedID":"1"},{"id":"22","name":"Test 2","associatedID":"2"},{"id":"32","name":"Test 3"}]
const result = _.differenceWith(array1, array2,
({ id }, { associatedID }) => id === associatedID
);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
答案 2 :(得分:1)
只需使用from datetime import timedelta as td
import datetime as da
#flex = input("Enter your flex amount in HHMM:")
flex = "0134"
now = da.datetime.now()
user_hours = int(flex[:2])
user_minute = int(flex[2:5])
delay = td(hours=user_hours, minutes=user_minute)
balance = da.datetime.now()+delay
print("Lunch: " +str(lunch))
print("Time when balance at 00:00 : " +str(balance))
print("Now: " +str(now))
和Array.filter
从Array.some
中获取与array1
不相关的项目:
array2
使用lodash也可以通过_.differenceWith完成此操作:
const array1 = [{ "id": "1", "name": "Test 1" }, { "id": "2", "name": "Test 2", }, { "id": "3", "name": "Test 3", } ]
const array2 = [{ "id": "12", "name": "Test 1", "associatedID": "1" }, { "id": "22", "name": "Test 2", "associatedID": "2" }, { "id": "32", "name": "Test 3", } ]
const result = array1.filter(x => !array2.some(y => y.associatedID == x.id))
console.log(result)
const array1 = [{ "id": "1", "name": "Test 1" }, { "id": "2", "name": "Test 2", }, { "id": "3", "name": "Test 3", } ]
const array2 = [{ "id": "12", "name": "Test 1", "associatedID": "1" }, { "id": "22", "name": "Test 2", "associatedID": "2" }, { "id": "32", "name": "Test 3", } ]
const result = _.differenceWith(array1, array2, (x,y) => x.id === y.associatedID)
console.log(result)