从JSON对象数组创建映射键值对

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

Create map key value from array of JSON object

问题

{
"I have a JSON array which looks like this -": "我有一个看起来像这样的JSON数组 -",
"Expected :": "期望:",
"Here is the attempt I made -": "这是我尝试的代码 -",
"let arr = [];": "let arr = [];",
"data.forEach((number, index, array) => {": "data.forEach((number, index, array) => {",
"let keys = Object.keys(array[index]);": "let keys = Object.keys(array[index]);",
"for(i in keys){": "for(i in keys){",
"let a = data.map(item => item[keys[i]]);": "let a = data.map(item => item[keys[i]]);",
"let b = keys[i];": "let b = keys[i];",
"arr.push({b:a});": "arr.push({b:a});",
"console.log(arr);": "console.log(arr);",
"Any help should be appreciated. Thanks!": "任何帮助都将不胜感激。谢谢!"
}

英文:

I have a JSON array which looks like this -

[
 {name: 'Alex', date: '05/17/2023 10:32 PM', id: '00153168', priority: '3-Medium'},
 {name: 'Peter', date: '05/17/2023 11:32 PM', id: '00153169', priority: '3-Medium'}
]

Expected :

{
name : ['Alex','Peter'],
date : ['05/17/2023 10:32 PM','05/17/2023 11:32 PM'],
id: ['00153168','00153169'],
priority: ['3-Medium', '3-Medium']
}

Here is the attempt I made -

let arr = [];
data.forEach((number, index, array) => {
let keys = Object.keys(array[index]);
    for(i in keys){
        let a = data.map(item => item[keys[i]]);
        let b = keys[i];
        arr.push({b:a});
        
    }
    console.log(arr);
});

Any help should be appreciated. Thanks!

答案1

得分: 1

如果您确定数组中所有对象的形状都是统一的,您可以首先使用数组中的第一个元素获取最终数据的键。

然后只需循环遍历这些键。在每次迭代中获取所有这些键的值。您可以使用map方法访问复杂对象中的嵌套元素。一旦获取了这些值,就可以将它们添加到一个新对象中。

当您遍历完所有键后,应该会得到您需要的数据形状。

const data = [
 {name: 'Alex', date: '05/17/2023 10:32 PM', id: '00153168', priority: '3-Medium'},
 {name: 'Peter', date: '05/17/2023 11:32 PM', id: '00153169', priority: '3-Medium'}
]

const keys = Object.keys(data[0]);
let consolidatedObject = {};

for (const key of keys){
  const keyData = data.map(x => x?.[key])
  consolidatedObject = {
    ...consolidatedObject,
    [key]: keyData
  }
}

console.log(consolidatedObject)

请注意,上述代码中的data.at(0)应更改为data[0],因为at方法不是JavaScript标准的数组方法。

英文:

If you know for sure that the shape of all of the objects in your array are uniform, you can first get the keys of your final data with the first element in your array.

Then just loop over your keys. Grabbing all of the values for each of those keys on every iteration. You can use map to access nested elements even in a complex object. Once you have the values, you can add them to a new object.

When you iterated over all your keys, you should have the data in the shape you need.

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

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

const data = [
 {name: &#39;Alex&#39;, date: &#39;05/17/2023 10:32 PM&#39;, id: &#39;00153168&#39;, priority: &#39;3-Medium&#39;},
 {name: &#39;Peter&#39;, date: &#39;05/17/2023 11:32 PM&#39;, id: &#39;00153169&#39;, priority: &#39;3-Medium&#39;}
]


const keys = Object.keys(data.at(0));
let consolidatedObject = {};

for (const key of keys){
  const keyData = data.map(x =&gt; x?.[key])
  consolidatedObject = {
    ...consolidatedObject,
    [key]: keyData
  }
}

console.log(consolidatedObject)

<!-- end snippet -->

答案2

得分: 1

你可以使用reduce

const arr = [
 {name: 'Alex', date: '05/17/2023 10:32 PM', id: '00153168', priority: '3-Medium'},
 {name: 'Peter', date: '05/17/2023 11:32 PM', id: '00153169', priority: '3-Medium'}
];

const o = arr.reduce((a, e) => {
  for (let k in e) {
    a[k] = a[k] || [];
    a[k].push(e[k]);
  }
  return a;
}, {});

console.log(o)
英文:

You might use reduce:

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

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

const arr = [
 {name: &#39;Alex&#39;, date: &#39;05/17/2023 10:32 PM&#39;, id: &#39;00153168&#39;, priority: &#39;3-Medium&#39;},
 {name: &#39;Peter&#39;, date: &#39;05/17/2023 11:32 PM&#39;, id: &#39;00153169&#39;, priority: &#39;3-Medium&#39;}
];

const o = arr.reduce((a, e) =&gt; {
  for (let k in e) {
    a[k] = a[k] || [];
    a[k].push(e[k]);
  }
  return a;
}, {});

console.log(o)

<!-- end snippet -->

答案3

得分: 1

const data = [
 {name: 'Alex', date: '05/17/2023 10:32 PM', id: '00153168', priority: '3-Medium'},
 {name: 'Peter', date: '05/17/2023 11:32 PM', id: '00153169', priority: '3-Medium'}
]

const result = data.reduce((a,c) => 
  (Object.entries(c).forEach(([k,v]) => (a[k]??=[]).push(v)), a), {})

console.log(result)
英文:

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

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

const data = [
 {name: &#39;Alex&#39;, date: &#39;05/17/2023 10:32 PM&#39;, id: &#39;00153168&#39;, priority: &#39;3-Medium&#39;},
 {name: &#39;Peter&#39;, date: &#39;05/17/2023 11:32 PM&#39;, id: &#39;00153169&#39;, priority: &#39;3-Medium&#39;}
]

const result = data.reduce((a,c) =&gt; 
  (Object.entries(c).forEach(([k,v]) =&gt; (a[k]??=[]).push(v)), a), {})

console.log(result)

<!-- end snippet -->

答案4

得分: 1

您可以使用Array#reduceObject.keysObject.assign方法如下所示:

const 
    input = [ {name: 'Alex', date: '05/17/2023 10:32 PM', id: '00153168', priority: '3-Medium'}, {name: 'Peter', date: '05/17/2023 11:32 PM', id: '00153169', priority: '3-Medium'} ],
      
    output = input.reduce(
        (a,c,i) => i === 0 ? c : Object.assign(
            a, Object.keys(c).reduce(
                (o,k) => Object.assign(
                    o, {[k]: Array.isArray(a[k]) ? [...a[k], c[k]] : [a[k], c[k]]}
                ), {}
            )
        ), {}
    );

console.log(output);
英文:

You can use Array#reduce, Object.keys and Object.assign methods as follows:

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

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

const 
      input = [ {name: &#39;Alex&#39;, date: &#39;05/17/2023 10:32 PM&#39;, id: &#39;00153168&#39;, priority: &#39;3-Medium&#39;}, {name: &#39;Peter&#39;, date: &#39;05/17/2023 11:32 PM&#39;, id: &#39;00153169&#39;, priority: &#39;3-Medium&#39;} ],
      
      output = input.reduce(
          (a,c,i) =&gt; i === 0 ? c : Object.assign(
              a,Object.keys(c).reduce(
                  (o,k) =&gt; Object.assign(
                      o,{[k]: Array.isArray(a[k]) ? [...a[k],c[k]] : [a[k],c[k]]}
                  ), {}
              )
          ), {}
      );
      
console.log( output );

<!-- end snippet -->

答案5

得分: 1

/** 将对象列表转换为列表对象
  * 保留数组中的缺失值,因此对象不必是统一的
  * 尽量简单,不使用减少器和重构
  */
function transpose(list) {
    const result = {};
    for (const i = 0; i < list.length; i++) {
        for (const [k, v] of Object.entries(list[i])) {
            (result[k] ??= [])[i] = v;
        }
    }
    return result;
}
英文:

playground

/** converts list of objects into object of lists
  * keeps missing values in arrays, so objects don&#39;t have to be uniform
  * as simple as possible, does not use reducers and reconstructing
  */
function transpose(list) {
    const result = {};
    for (const i = 0; i &lt; list.length; i++) {
        for (const [k, v] of Object.entries(list[i])) {
            (result[k] ??= [])[i] = v;
        }
    }
    return result;
}

huangapple
  • 本文由 发表于 2023年6月22日 01:38:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76525883.html
匿名

发表评论

匿名网友

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

确定