js简写,能不能用一行写出来

看注释,希望能用一句写出来,有没有这种简便写法?

const t = [
  {name: 'John', value: 111},
  {name: 'Mary', value: 222}
];

const param = t.reduce((p, n) => {
  // 这儿能不能用一行写出来,类似于这样 t.map(k => k.child);
  p[n.name] = n.value;
  return p;
}, {})
阅读 8.4k
5 个回答
const t = [
  {name: 'John', value: 111},
  {name: 'Mary', value: 222}
];
const param = t.reduce((p, n) => (p[n.name] = n.value,p), {})

巧了这个问题我最近也思考过

t.reduce((p, n) => ({...p, [n.name]: n.value}), {})

以下的方法,性能都没有以上被采纳的方法快

const t = [
  {name: 'John', value: 111},
  {name: 'Mary', value: 222}
];
const param = Object.fromEntries(t.map(({name,value})=>[name,value]))
//结果
{
John: 111,
Mary: 222
}
const t = [
  {name: 'John', value: 111},
  {name: 'Mary', value: 222}
];
const param = Object.assign({}, ...t.map(({name,value})=>({[name]:value})))
//结果
{
John: 111,
Mary: 222
}
const t = [
  {name: 'John', value: 111},
  {name: 'Mary', value: 222}
];
const param = t.reduce((p, n) => Object.assign(p,{[n.name] : n.value}), {})
//结果
{
John: 111,
Mary: 222
}
const t = [
  { name: 'John', value: 111 },
  { name: 'Mary', value: 222 }
];

const param = t.reduce((p, n) => ({ ...p, [n.name]: n.value }), {})
const t = [
  {name: 'John', value: 111},
  {name: 'Mary', value: 222}
];

const res = Array.from(t, item => { return { [item.name]: item.value }})
推荐问题
宣传栏