给出以下示例:
foobar: [
{
"foo": {
"title": "example title foo"
"desc": "example description foo"
}
},
{
"bar": {
"title": "example title bar",
"unnecessary": "this is not needed"
"desc": "example description bar",
}
}
]
如何格式化包含您得到以下结果的对象的数组:
[
{"example title foo": "example description foo"},
{"example title bar": "example description bar"}
]
答案 0 :(得分:0)
您可以使用Object.values
和map
。使用Computed property names创建所需的对象
let foobar = [{"foo":{"title":"example title foo","desc":"example description foo"}},{"bar":{"title":"example title bar","unnecessary":"this is not needed","desc":"example description bar"}}]
let output = foobar.map(a => {
let { title, desc } = Object.values(a)[0];
return { [title] : desc }
})
console.log(output)
答案 1 :(得分:0)
您可以获取单个值的对象,对其进行解构并映射所需的样式。
var foobar = [{ foo: { title: "example title foo", desc: "example description foo" } }, { bar: { title: "example title bar", unnecessary: "this is not needed", desc: "example description bar" } }],
pattern = ({ title, desc }) => ({ [title]: desc }),
result = foobar.map(o => pattern(Object.values(o)[0]));
console.log(result);