[英]How find properties in an array in object and move these objects to another array in the object?
如何在對象的數組中查找屬性並將這些對象移動到對象中的另一個數組? 如何提取{“評論”:“值”}從this.state.comments
,並將其放置在comment
中對象comments
的其他對象后陣列? 我重新映射了數組並提取了值本身- comment properties
。 如何提取整個對象,使其看起來像這樣{“ comment:” value“}
const comment = {
"comments": [{'comment': 'aaa'}, {'comment': 'bbb'}]
"description": " ytytyty"
"id": 3
"title": "gfgfgfgfgf"
}
this.state.comments = [
{"comment": "eeeee"},
{"comment": "rrrrr"},
{"comment": "ggggg"},
{"date: Thu Jun 13 2019 01:27:09
"desc": "dfdfdf"
"comment": "hhhhhh"
}
]
let v = this.state.comments.map(t => t.comment? t.comment : t);
console.log(`{comment: ${v}`);
預期效果:
const comment = {
"comments": [{'comment': 'aaa'}, {'comment': 'bbb'},
{"comment": "eeeee"}, {"comment": "rrrrr"}, {"comment":
"ggggg"}, "comment": "hhhhhh"]
"description": " ytytyty"
"id": 3
"title": "gfgfgfgfgf"
}
const comment = { comments: [{comment: 'aaa'}, {comment: 'bbb'}], description: " ytytyty", id: 3, title: "gfgfgfgfgf" } const newComments = [ {comment: "eeeee"}, {comment: "rrrrr"}, {comment: "ggggg"}, {date: "Thu Jun 13 2019 01:27:09", desc: "dfdfdf", comment: "hhhhhh" } ]; comment.comments = newComments.reduce((res,obj) => obj.comment ? [...res, {comment : obj.comment}] : res,comment.comments || []) console.log(comment);
const comment = { "comments": [{'comment': 'aaa'}, {'comment': 'bbb'}], "description": " ytytyty", "id": 3, "title": "gfgfgfgfgf" } let newComments = [ {"comment": "eeeee"}, {"comment": "rrrrr"}, {"comment": "ggggg"}, {"date": "Thu Jun 13 2019 01:27:09", "desc": "dfdfdf", "comment": "hhhhhh" } ] newComments.forEach(t => { if( t.comment ) comment.comments.push({ comment: t.comment }) }); console.log(comment);
只需使用forEach
遍歷每個項目,然后檢查鍵是否為comment
-如果是,則推送到comments
數組。
const comment = {"comments":[{'comment':'aaa'},{'comment':'bbb'}], "description":" ytytyty", "id":3, "title":"gfgfgfgfgf"}; const state = {comments:[{"comment":"eeeee"},{"comment":"rrrrr"},{"comment":"ggggg"},{"date":"Thu Jun 13 2019 01:27:09", "desc":"dfdfdf", "comment":"hhhhhh"}]}; state.comments.forEach(({ comment: c }) => c ? comment.comments.push({ c }) : c); console.log(comment);
.as-console-wrapper { max-height: 100% !important; top: auto; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.