如何将键值对对象数组转换为 JavaScript 中的二维数组

huangapple go评论71阅读模式
英文:

How to convert key-value object array into 2d array in javascript

问题

You can create the final array without using forEach and map by using a simple for loop. Here's an example of how you can do it:

let th = ['name', 'id', 'class'];

let arr = [
    { 'name': 'a', 'class': '7', 'id': '1' },
    { 'name': 'b', 'class': '7', 'id': '2' },
    { 'name': 'b', 'class': '7', 'id': '3' },
    { 'name': 'd', 'class': '7', 'id': '4' }
];

let finalArr = [];

for (let i = 0; i < arr.length; i++) {
    let innerArr = [];
    for (let j = 0; j < th.length; j++) {
        innerArr.push(arr[i][th[j]]);
    }
    finalArr.push(innerArr);
}

console.log(finalArr);

This code will create the finalArr array without using forEach and map.

英文:

<!-- language: lang-js -->

let th = [&#39;name&#39;, &#39;id&#39;, &#39;class&#39;]
    
let arr = [
    { &#39;name&#39; : &#39;a&#39;, &#39;class&#39;:&#39;7&#39;, &#39;id&#39;:&#39;1&#39; },
    { &#39;name&#39; : &#39;b&#39;, &#39;class&#39;:&#39;7&#39;, &#39;id&#39;:&#39;2&#39; },
    { &#39;name&#39; : &#39;b&#39;, &#39;class&#39;:&#39;7&#39;, &#39;id&#39;:&#39;3&#39; },
    { &#39;name&#39; : &#39;d&#39;, &#39;class&#39;:&#39;7&#39;, &#39;id&#39;:&#39;4&#39; }
]
    
/* final array what is look like */
    
let finalArr = [
    [&#39;a&#39;, &#39;1&#39;, &#39;7&#39;],
    [&#39;b&#39;, &#39;2&#39;, &#39;7&#39;],
    [&#39;c&#39;, &#39;3&#39;, &#39;7&#39;],
    [&#39;d&#39;, &#39;4&#39;, &#39;7&#39;]
]

How can I create this array without using forEach and map? This is a sample data, but in reality there are more than 10k data at a time so forEach is not a good option.

答案1

得分: 5

你在第三行有个拼写错误,已在此处修复:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let th = ['name', 'id', 'class'];

let arr = [
    { 'name': 'a', 'class': '7', 'id': '1' },
    { 'name': 'b', 'class': '7', 'id': '2' },
    { 'name': 'c', 'class': '7', 'id': '3' },
    { 'name': 'd', 'class': '7', 'id': '4' }
];

const transformedArr = arr.map(row => th.map(name => row[name]));
console.log(transformedArr);

<!-- end snippet -->
英文:

You have a typo in the third row, fixed here:
<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let th = [&#39;name&#39;, &#39;id&#39;, &#39;class&#39;];

let arr = [
    { &#39;name&#39;: &#39;a&#39;, &#39;class&#39;: &#39;7&#39;, &#39;id&#39;: &#39;1&#39; },
    { &#39;name&#39;: &#39;b&#39;, &#39;class&#39;: &#39;7&#39;, &#39;id&#39;: &#39;2&#39; },
    { &#39;name&#39;: &#39;c&#39;, &#39;class&#39;: &#39;7&#39;, &#39;id&#39;: &#39;3&#39; },
    { &#39;name&#39;: &#39;d&#39;, &#39;class&#39;: &#39;7&#39;, &#39;id&#39;: &#39;4&#39; }
];

const transformedArr = arr.map(row =&gt; th.map(name =&gt; row[name]));
console.log(transformedArr);

<!-- end snippet -->

A potentially faster one, but actually slower up to 2x times than the above solution (tested in node.js / Chrome with 40000000 items in the arr, in Firefox seems the same, but it hangs on that amount of data):

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let th = [&#39;name&#39;, &#39;id&#39;, &#39;class&#39;];

let arr = [
    { &#39;name&#39;: &#39;a&#39;, &#39;class&#39;: &#39;7&#39;, &#39;id&#39;: &#39;1&#39; },
    { &#39;name&#39;: &#39;b&#39;, &#39;class&#39;: &#39;7&#39;, &#39;id&#39;: &#39;2&#39; },
    { &#39;name&#39;: &#39;c&#39;, &#39;class&#39;: &#39;7&#39;, &#39;id&#39;: &#39;3&#39; },
    { &#39;name&#39;: &#39;d&#39;, &#39;class&#39;: &#39;7&#39;, &#39;id&#39;: &#39;4&#39; }
];

const transformedArr = [];

for (let i = 0; i &lt; arr.length; i++) {
    const item = [];
    for (let j = 0; j &lt; th.length; j++) {
        item.push(arr[i][th[j]]);
    }
    transformedArr.push(item);
}

console.log(transformedArr);

<!-- end snippet -->

答案2

得分: 1

以下是您要翻译的内容:

您可能会对 Array.map / Array.forEach 的性能表现感到惊讶(特别是 map)。以下是不同方法的性能测试:

const arr4Test = [...Array(10000)].map((_, i) => ({name: `a`, class: 1, id: i}));
let finalArr = [];

// for ... of
let perf = performance.now();
for (let obj of arr4Test) {
  finalArr.push(Object.values(obj));
}
perf = (performance.now() - perf).toFixed(5);
console.log(`for ... of ${JSON.stringify(finalArr.slice(0, 3))} ... ${perf}ms`);

// classic loop
perf = performance.now();
finalArr.length = 0;
for (let i = 0; i < arr4Test.length; i += 1) {
  let tmpArr = [];
  
  for (let key in arr4Test[i]) {
    tmpArr.push(arr4Test[i][key])
  }
  
  finalArr.push(tmpArr);
}

perf = (performance.now() - perf).toFixed(5);
console.log(`classic loop ${JSON.stringify(finalArr.slice(0, 3))} ... ${perf}ms`);

// map
perf = performance.now();
finalArr = arr4Test.map(Object.values);
perf = (performance.now() - perf).toFixed(5);
console.log(`map => ${JSON.stringify(finalArr.slice(0, 3))} ... ${perf}ms`);

// forEach
finalArr.length = 0;
perf = performance.now();
arr4Test.forEach(v => finalArr.push(Object.values(v)));
perf = (performance.now() - perf).toFixed(5);
console.log(`forEach => ${JSON.stringify(finalArr.slice(0, 3))} ... ${perf}ms`);

请告诉我您需要的进一步帮助。

英文:

You may be surprised by the performance of Array.map/Array.forEach (especially map). Here are performance tests for different approaches:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const arr4Test = [...Array(10000)].map((_, i) =&gt; ({name: `a`, class: 1, id: i}));
let finalArr = [];
// for ... of
let perf = performance.now();
for (let obj of arr4Test) {
finalArr.push(Object.values(obj));
}
perf = (performance.now() - perf).toFixed(5);
console.log(`for ... of ${JSON.stringify(finalArr.slice(0, 3))} ... ${perf}ms`);
// classic loop
perf = performance.now();
finalArr.length = 0;
for (let i = 0; i &lt; arr4Test.length; i += 1) {
let tmpArr = [];
for (let key in arr4Test[i]) {
tmpArr.push(arr4Test[i][key])
}
finalArr.push(tmpArr);
}
perf = (performance.now() - perf).toFixed(5);
console.log(`classic loop ${JSON.stringify(finalArr.slice(0, 3))} ... ${perf}ms`);
// map
perf = performance.now();
finalArr = arr4Test.map(Object.values);
perf = (performance.now() - perf).toFixed(5);
console.log(`map =&gt; ${JSON.stringify(finalArr.slice(0, 3))} ... ${perf}ms`);
// forEach
finalArr.length = 0;
perf = performance.now();
arr4Test.forEach(v =&gt; finalArr.push(Object.values(v)));
perf = (performance.now() - perf).toFixed(5);
console.log(`forEach =&gt; ${JSON.stringify(finalArr.slice(0, 3))} ... ${perf}ms`);

<!-- end snippet -->

答案3

得分: 0

Regarding the Kooilinc's answer. Benchmarked the options and I think the classic loop test is not good, Object.values should be used as well as in the other tests otherwise it's unequal conditions:

<script name="benchmark" data-count="1000">

const arr4Test = [...Array(10000)].map((_, i) => ({name: `a`, class: 1, id: i}));
let finalArr = [];

// @benchmark for...off
finalArr.length = 0;
for (let obj of arr4Test) {
  finalArr.push(Object.values(obj));
}
finalArr;

// @benchmark classic loop
finalArr.length = 0;
for (let i = 0; i < arr4Test.length; i += 1) {
  let tmpArr = [];
  
  for (let key in arr4Test[i]) {
    tmpArr.push(arr4Test[i][key])
  }
  
  finalArr.push(tmpArr);
}
finalArr;

// @benchmark map
finalArr = arr4Test.map(Object.values);
finalArr;

// @benchmark forEach
finalArr.length = 0;
arr4Test.forEach(v => finalArr.push(Object.values(v)));
finalArr;

</script>
<script src="https://raw.githack.com/silentmantra/benchmark/master/benchmark.min.js"></script>

(Note: I have provided the translated content you requested without additional information or responses.)

英文:

Regarding the Kooilinc's answer. Benchmarked the options and I think the classic loop test is not good, Object.values should be used as well as in the other tests otherwise it's unequal conditions:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

&lt;script name=&quot;benchmark&quot; data-count=&quot;1000&quot;&gt;
const arr4Test = [...Array(10000)].map((_, i) =&gt; ({name: `a`, class: 1, id: i}));
let finalArr = [];
// @benchmark for...off
finalArr.length = 0;
for (let obj of arr4Test) {
finalArr.push(Object.values(obj));
}
finalArr;
// @benchmark classic loop
finalArr.length = 0;
for (let i = 0; i &lt; arr4Test.length; i += 1) {
let tmpArr = [];
for (let key in arr4Test[i]) {
tmpArr.push(arr4Test[i][key])
}
finalArr.push(tmpArr);
}
finalArr;
// @benchmark map
finalArr = arr4Test.map(Object.values);
finalArr;
// @benchmark forEach
finalArr.length = 0;
arr4Test.forEach(v =&gt; finalArr.push(Object.values(v)));
finalArr;
&lt;/script&gt;
&lt;script src=&quot;https://raw.githack.com/silentmantra/benchmark/master/benchmark.min.js&quot;&gt;&lt;/script&gt;

<!-- end snippet -->

答案4

得分: 0

You just need to push a new array to finalArr using .map and the order you want of the columns.

let arr = [
    { 'name' : 'a', 'class':'7', 'id':'1' },
    { 'name' : 'b', 'class':'7', 'id':'2' },
    { 'name' : 'b', 'class':'7', 'id':'3' },
    { 'name' : 'd', 'class':'7', 'id':'4' }
    ]
    
let finalArr = [];

arr.map(row => {
  finalArr.push([row.name, row.id, row.class]);
})

console.log(finalArr);
英文:

You just need to push a new array to finalArr using .map and the order you want of the columns.

let arr = [
{ &#39;name&#39; : &#39;a&#39;, &#39;class&#39;:&#39;7&#39;, &#39;id&#39;:&#39;1&#39; },
{ &#39;name&#39; : &#39;b&#39;, &#39;class&#39;:&#39;7&#39;, &#39;id&#39;:&#39;2&#39; },
{ &#39;name&#39; : &#39;b&#39;, &#39;class&#39;:&#39;7&#39;, &#39;id&#39;:&#39;3&#39; },
{ &#39;name&#39; : &#39;d&#39;, &#39;class&#39;:&#39;7&#39;, &#39;id&#39;:&#39;4&#39; }
]
let finalArr = [];
arr.map(row =&gt; {
finalArr.push([row.name, row.id, row.class]);
})
console.log(finalArr);

答案5

得分: 0

Here's the translated code snippet:

let th = ['name', 'id', 'class'];

let arr = [{
    'name': 'a',
    'class': '7',
    'id': '1'
  },
  {
    'name': 'b',
    'class': '7',
    'id': '2'
  },
  {
    'name': 'b',
    'class': '7',
    'id': '3'
  },
  {
    'name': 'd',
    'class': '7',
    'id': '4'
  }
];

let data = arr.map((e) => ([e.name, e.id, e.class]));
console.log(data);

let data1 = arr.map((e) => th.map((j) => e[j]))
console.log(data1);

console.log(arr.map((e) => (Object.values(e))));

Please note that the code itself remains in JavaScript, and only the comments and string content are translated into Chinese.

英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let th = [&#39;name&#39;, &#39;id&#39;, &#39;class&#39;]
let arr = [{
&#39;name&#39;: &#39;a&#39;,
&#39;class&#39;: &#39;7&#39;,
&#39;id&#39;: &#39;1&#39;
},
{
&#39;name&#39;: &#39;b&#39;,
&#39;class&#39;: &#39;7&#39;,
&#39;id&#39;: &#39;2&#39;
},
{
&#39;name&#39;: &#39;b&#39;,
&#39;class&#39;: &#39;7&#39;,
&#39;id&#39;: &#39;3&#39;
},
{
&#39;name&#39;: &#39;d&#39;,
&#39;class&#39;: &#39;7&#39;,
&#39;id&#39;: &#39;4&#39;
}
];
let data = arr.map((e) =&gt; ([e.name, e.id, e.class]));
console.log(data);
let data1 = arr.map((e) =&gt; th.map((j) =&gt; e[j]))
console.log(data1);
console.log(arr.map((e) =&gt; (Object.values(e))));

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月10日 15:25:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76215894.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定