这里有两个对象,如果在object2中找到,我需要比较它们并从object1返回特定值。
object1 = {
"body": {
"items": [
{
"data": {
"name": "Smith",
"status": "Ready",
"userinfo": [
{
"dob": "01/01/2000",
"nickname": "Joe"
}
]
},
"workinfo": {
"company": "mycompany",
"address": "101 Main str."
}
},
{
"data": {
"name": "Luke",
"status": "Ready",
"userinfo": [
{
"dob": "01/01/2001",
"nickname": "LL"
}
]
},
"workinfo": {
"company": "mycompany",
"address": "101 Main str."
}
}
]
}
}
Object2甚至很简单:
object2 = {
"items": [
{
"name": "Smith",
"status": "Ready"
},
{
"name": "Luke",
"status": "Ready"
}
]
}
因此,如果在Object2 items.name中找到了Object1 body.items [x] .data.name,那么最后我需要获得这样的新对象:
object3 = {{name: "Smith", status: "Ready"}, {name: "Luke", status: "Ready"}}
答案 0 :(得分:1)
您可以使用过滤器查找:
var obj1 = {
"body": {
"items": [{
"data": {
"name": "Smith",
"status": "Ready",
"userinfo": [{
"dob": "01/01/2000",
"nickname": "Joe"
}]
},
"workinfo": {
"company": "mycompany",
"address": "101 Main str."
}
},
{
"data": {
"name": "Luke",
"status": "Ready",
"userinfo": [{
"dob": "01/01/2001",
"nickname": "LL"
}]
},
"workinfo": {
"company": "mycompany",
"address": "101 Main str."
}
}
]
}
}
var obj2 = {
"items": [{
"name": "Smith",
"status": "Ready"
},
{
"name": "Luke",
"status": "Ready"
}
]
}
var output = obj2.items.filter(({name}) => obj1.body.items.find(({data}) => name === data.name))
console.log(output)
过滤器将返回所有通过查找条件的对象,也就是说,如果名称在obj1中找到
答案 1 :(得分:0)
您可以使用_.intersectionWith()
从obj2
返回项目,它们的name
等于data.name
项目中的obj2
:
const obj1 = {"body":{"items":[{"data":{"name":"Smith","status":"Ready","userinfo":[{"dob":"01/01/2000","nickname":"Joe"}]},"workinfo":{"company":"mycompany","address":"101 Main str."}},{"data":{"name":"Luke","status":"Ready","userinfo":[{"dob":"01/01/2001","nickname":"LL"}]},"workinfo":{"company":"mycompany","address":"101 Main str."}}]}}
const obj2 = {"items":[{"name":"Smith","status":"Ready"},{"name":"Luke","status":"Ready"}]}
const result = _.intersectionWith(obj2.items, obj1.body.items,
(a, b) => _.get(a, 'name') === _.get(b, 'data.name')
)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
答案 2 :(得分:0)
使用ES6,使用Array.filter和Array.some可以轻松完成任务:
const obj1 = {"body":{"items":[{"data":{"name":"Smith","status":"Ready","userinfo":[{"dob":"01/01/2000","nickname":"Joe"}]},"workinfo":{"company":"mycompany","address":"101 Main str."}},{"data":{"name":"Luke","status":"Ready","userinfo":[{"dob":"01/01/2001","nickname":"LL"}]},"workinfo":{"company":"mycompany","address":"101 Main str."}}]}}
const obj2 = {"items":[{"name":"Smith","status":"Ready"},{"name":"Luke","status":"Ready"}]}
const r = obj2.items.filter(x => obj1.body.items.some(y => y.data.name == x.name))
console.log(r)
由于对象在obj2
中具有正确的布局,因此可以从此处开始并针对obj1
进行过滤。