这个问题在这里已有答案:
是否有可能将嵌套数组对象展平为单个对象。在我的查询中,我想删除源对象并将结果对象作为一个对象(我也提到了我的输出)。
var result = [
{"_id":"12345",
"_type":"feeds",
"_source":{
"title": "hi all solve it",
"link": "www.face.com",
"content": "Hi thewwewewedwe asdasdasdasd",
"createdAt": "2018-08-08T11:42:40.073Z",
"updatedAt": "2018-08-08T11:42:40.073Z",
"reply": []
}
}]
//resultant array
var newResult = [
{
"_id":"12345",
"_type":"feeds",
"title": "hi all solve it",
"link": "www.face.com",
"content": "Hi thewwewewedwe asdasdasdasd",
"createdAt": "2018-08-08T11:42:40.073Z",
"updatedAt": "2018-08-08T11:42:40.073Z",
"reply": []
}];
使用普通JS的最简单版本
处理多个条目
var result = [{ "_id": "12345", "_type": "feeds", "_source": { "title": "hi all solve it", "link": "www.face.com", "content": "Hi thewwewewedwe asdasdasdasd", "createdAt": "2018-08-08T11:42:40.073Z", "updatedAt": "2018-08-08T11:42:40.073Z", "reply": [] } },{ "_id": "12346", "_type": "feeds", "_source": { "title": "hi all solve it", "link": "www.face.com", "content": "Hi thewwewewedwe asdasdasdasd", "createdAt": "2018-08-08T11:42:40.073Z", "updatedAt": "2018-08-08T11:42:40.073Z", "reply": [] } }]
result = result.map(function(item) {
var obj = item._source;
for (var o in item) {
if (o != "_source") obj[o] = item[o];
}
return obj;
})
console.log(result)
你可以使用...spread
var result = [{
"_id":"12345",
"_type":"feeds",
"_source": {
"title": "hi all solve it",
"link": "www.face.com",
"content": "Hi thewwewewedwe asdasdasdasd",
"createdAt": "2018-08-08T11:42:40.073Z",
"updatedAt": "2018-08-08T11:42:40.073Z",
"reply": []
}
}];
const { _source, ...rest } = result[0];
const flattenResult = [{
...rest,
..._source,
}];
console.log(flattenResult);
将result.length> 1的解决方案作为练习留给您。
您可以首先遍历数组以获取数组中的每个对象,然后遍历对象键以获取key
名称。然后,如果遇到名为key
的_source
,则使用Object.assign()
将这些对象内容分配到展平对象中。这适用于带有一个或多个对象的result
数组。
var result = [{
"_id": "12345",
"_type": "feeds",
"_source": {
"title": "hi all solve it",
"link": "www.face.com",
"content": "Hi thewwewewedwe asdasdasdasd",
"createdAt": "2018-08-08T11:42:40.073Z",
"updatedAt": "2018-08-08T11:42:40.073Z",
"reply": []
}
},
{
"_id": "1234567",
"_type": "feeds123",
"_source": {
"title": "hi all solve it 123",
"link": "www.face.com",
"content": "Hi thewwewewedwe asdasdasdasd",
"createdAt": "2018-08-08T11:42:40.073Z",
"updatedAt": "2018-08-08T11:42:40.073Z",
"reply": []
}
}];
var newArray = [];
result.forEach(function(obj){
var tempObj = {};
Object.keys(obj).forEach(function(key){
if(key !== '_source'){
tempObj[key] = obj[key];
} else {
tempObj = Object.assign(tempObj, obj[key]);
}
});
newArray.push(tempObj);
});
console.log(newArray);