如何在对象的数组中查找属性并将这些对象移动到对象中的另一个数组?如何从this.state.comments
中提取{“ comment”:“ value”}并将其放置在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"
}
答案 0 :(得分:1)
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);
答案 1 :(得分:1)
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);
答案 2 :(得分:0)
只需使用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; }