是否有可能将嵌套数组对象展平为单个对象。在我的查询中,我想删除源对象并将生成的对象作为一个对象(我也提到了我的输出)。
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": []
}];
答案 0 :(得分:1)
您可以为此使用...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的解决方案。
答案 1 :(得分:0)
您可以先遍历数组以获取数组中的每个对象,然后遍历对象键以获取key
名称。然后,如果遇到名称为key
的{{1}},则使用_source
将那些对象内容分配给扁平对象。这将适用于具有一个或多个对象的Object.assign()
数组。
result
答案 2 :(得分:0)
使用普通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)