我有以下
{
bill: [
{ satisfy: 'true', comments: '' }
],
permission_title: [
{ satisfy: 'false', comments: '5' }
],
final_status: [
{ satisfy: 'true', comments: '' }
]
}
我需要发送:
{
bill: { satisfy: 'true', comments: '' },
permission_title: { satisfy: 'false', comments: '5' },
final_status: { satisfy: 'true', comments: '' }
}
获得它的最佳和快捷方式是什么?
答案 0 :(得分:2)
使用Object.entries()
提取键/值对(条目)。使用Array.map()
迭代条目。对于每个条目,返回一个带有键的对象,以及没有包装数组的值。通过spreading合并回Object.assign()
对象:
const obj = {"bill":[{"satisfy":"true","comments":""}],"permission_title":[{"satisfy":"false","comments":"5"}],"final_status":[{"satisfy":"true","comments":""}]};
const result = Object.assign(
...Object.entries(obj).map(([k, v]) => ({
[k]: v[0]
}))
);
console.log(result);
答案 1 :(得分:2)
我们假设您的对象名为 obj 。我会这样做:
for(var p in obj) obj[p] = obj[p][0];
const obj={
bill: [
{ satisfy: 'true', comments: '' }
],
permission_title: [
{ satisfy: 'false', comments: '5' }
],
final_status: [
{ satisfy: 'true', comments: '' }
]
}
let obj_new=Object.assign(obj);
for(var p in obj_new) { obj_new[p] = obj_new[p][0] };
console.log(obj_new);

答案 2 :(得分:0)
假设每个值只有一个索引,另一种方法是使用函数reduce
和函数Object.keys
。
var obj = { bill: [{ satisfy: 'true', comments: '' }], permission_title: [{ satisfy: 'false', comments: '5' }], final_status: [{ satisfy: 'true', comments: '' }]},
result = Object.keys(obj).reduce((a, k) => (Object.assign(a, {[k]: obj[k][0]})), {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 3 :(得分:0)
const src = {
bill: [
{ satisfy: 'true', comments: '' }
],
permission_title: [
{ satisfy: 'false', comments: '5' }
],
final_status: [
{ satisfy: 'true', comments: '' }
]
};
const dest = Object.keys(src).reduce((prev, key) => {
prev[key] = src[key][0];
return prev;
}, {});
console.log(dest);
答案 4 :(得分:0)
我不确定效率,但你也可以使用find功能!
const src = {
bill: [
{ satisfy: 'true', comments: '' }
],
permission_title: [
{ satisfy: 'false', comments: '5' }
],
final_status: [
{ satisfy: 'true', comments: '' }
]
};
const dest = Object.keys(src).reduce((prev, key) => {
if(Array.isArray(src[key])) {
prev[key] = src[key].find(() => true);
}
return prev;
}, {});
console.log(dest);