[英]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.