将对象属性中的数组扩展到对象数组

发布于 2025-02-09 00:53:28 字数 285 浏览 2 评论 0原文

我如何将以下对象转换

data = {
  sp: [ 'A', 'B', 'C' ],
  jh: [ '1', '0', 'AB' ],
  oa: [ 27493, 9837, 3781 ]
}

为以下对象数组:

new_data = [
  {sp: 'A', jh: '1', oa: 27493},
  {sp: 'B', jh: '0', oa: 9837},
  {sp: 'C', jh: 'AB', oa: 3781}
]

How am I able to convert the following object:

data = {
  sp: [ 'A', 'B', 'C' ],
  jh: [ '1', '0', 'AB' ],
  oa: [ 27493, 9837, 3781 ]
}

into the following array of objects:

new_data = [
  {sp: 'A', jh: '1', oa: 27493},
  {sp: 'B', jh: '0', oa: 9837},
  {sp: 'C', jh: 'AB', oa: 3781}
]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

绝不服输 2025-02-16 00:53:28

假设数组的大小相同,MAP使用当前索引 <代码>降低键。

const data = {
  sp: [ 'A', 'B', 'C' ],
  jh: [ '1', '0', 'AB' ],
  oa: [ 27493, 9837, 3781 ]
};

let keys = Object.keys(data);
let new_data = data[keys[0]].map(( _, idx ) => keys.reduce((a, c) => ({ ...a, [c]: data[c][idx] }), {}));

console.log(new_data)
.as-console-wrapper { max-height: 100% !important; top: auto; }

Assuming the arrays are all the same size, map one of them and reduce the keys using the current index.

const data = {
  sp: [ 'A', 'B', 'C' ],
  jh: [ '1', '0', 'AB' ],
  oa: [ 27493, 9837, 3781 ]
};

let keys = Object.keys(data);
let new_data = data[keys[0]].map(( _, idx ) => keys.reduce((a, c) => ({ ...a, [c]: data[c][idx] }), {}));

console.log(new_data)
.as-console-wrapper { max-height: 100% !important; top: auto; }

并安 2025-02-16 00:53:28
  1. 您可以使用 /code> 获取对象中的所有键值对。
  2. 假设对象中的所有数组均具有相同的长度,则可以将第一个条目的数组值的长度作为输出的长度作为输出。
  3. 然后,您可以映射所有可能的索引并使用 object.fromentries 用原始对象的键创建一个对象,并且值为原始对象中该键的数个数组中该索引的值。
const data = {
  sp: [ 'A', 'B', 'C' ],
  jh: [ '1', '0', 'AB' ],
  oa: [ 27493, 9837, 3781 ]
}
let entries = Object.entries(data);
let res = entries[0][1].map((_, i)=>Object.fromEntries(
                              entries.map(([k, v])=>[k, v[i]])));
console.log(res);

  1. You can use Object.entries to get all of the key-value pairs in the object.
  2. You can take the length of the values of the array for the first entry as the length of the output, assuming that all of the arrays in the object are of the same length.
  3. Then, you can map over all of the possible indexes and use Object.fromEntries to create an object with the keys from the original object and the value being the value at that index in the array for that key in the original object.

const data = {
  sp: [ 'A', 'B', 'C' ],
  jh: [ '1', '0', 'AB' ],
  oa: [ 27493, 9837, 3781 ]
}
let entries = Object.entries(data);
let res = entries[0][1].map((_, i)=>Object.fromEntries(
                              entries.map(([k, v])=>[k, v[i]])));
console.log(res);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文