简体   繁体   English

Javascript-将给定对象简化为一个数据结构

[英]Javascript - reduce the given object into one data structure

I need to reduce the given object into some datastructure. 我需要将给定的对象简化为某些数据结构。 This is my input object. 这是我的输入对象。

const receiver =  {
      USER1: {
        module: ['a_critical', 'a_normal','b_normal']
      },
      USER2: {
        module: ['a_critical', 'a_normal','b_critical']
      }, 
      USER3: {
        module: ['a_critical']
      }
    };

const allModules = ['a_normal', 'a_critical', 'b_normal', 'b_critical']; 

Desired output: 所需的输出:

{
  "a_critical": [
    {
      "user": [
        "USER1", "USER2", "USER3"
      ]
    }
  ],
  "a_normal": [
    {
      "user": [
        "USER1", "USER2"
      ]
    }
 ],
  "b_normal": [
    {
      "user": [
        "USER1"
      ]
    }
  ],
  "b_critical": [
    {
      "user": [
        "USER2"
      ]
    }
  ]
} 

I have tried doing but i was getting some problems. 我尝试做,但是遇到了一些问题。 I am getting some duplicate properties which should be there. 我得到一些应该存在的重复属性。 I can share the code on what i have tried. 我可以分享我尝试过的代码。

const receiverObj = {};

let count = 0;
Object.keys(receiver).forEach((item) => {
    receiver[item].module.forEach((module) => {
      if(allModules.includes(module)) {
        count  = 1;
        if(count) {
        receiverObj[module] = [];
           receiverObj[module].push({user: [item] });
        }
        receiverObj[module].push({user: item });
        count = 0;
      }
    })
});

console.log(JSON.stringify(receiverObj, null, 2)); 

Actual result which i got: 我得到的实际结果:

{
  "a_critical": [
    {
      "user": [
        "USER3"
      ]
    },
    {
      "user": "USER3"
    }
  ],
  "a_normal": [
    {
      "user": [
        "USER2"
      ]
    },
    {
      "user": "USER2"
    }
  ],
  "b_normal": [
    {
      "user": [
        "USER1"
      ]
    },
    {
      "user": "USER1"
    }
  ],
  "b_critical": [
    {
      "user": [
        "USER2"
      ]
    },
    {
      "user": "USER2"
    }
  ]
} 

Is there any optimal way of doing this ? 有什么最佳的方法吗? can someone help ? 有人可以帮忙吗?

Iterate over each module in a reduce callback, creating a { user: [] } object in the accumulator if it doesn't exist yet, and then push to that array: 遍历reduce回调中的每个module ,如果尚未在累加器中创建{ user: [] }对象,然后将其压入该数组:

 const receiver = { USER1: { module: ['a_critical', 'a_normal','b_normal'] }, USER2: { module: ['a_critical', 'a_normal','b_critical'] }, USER3: { module: ['a_critical'] } }; const output = Object.entries(receiver) .reduce((a, [user, { module }]) => { module.forEach((name) => { if (!a[name]) { a[name] = { user: [] }; } a[name].user.push(user); }); return a; }, {}); console.log(output); 

You could also create the accumulator object in advance, if you wanted, since you have allModules , thereby avoiding conditionals inside the .reduce : 你也可以事先创建累加器对象,如果你想,既然你有allModules ,从而避免了内部条件句.reduce

 const receiver = { USER1: { module: ['a_critical', 'a_normal','b_normal'] }, USER2: { module: ['a_critical', 'a_normal','b_critical'] }, USER3: { module: ['a_critical'] } }; const allModules = ['a_normal', 'a_critical', 'b_normal', 'b_critical']; const accum = Object.fromEntries( allModules.map( name => [name, { user: [] }] ) ); const output = Object.entries(receiver) .reduce((a, [user, { module }]) => { module.forEach((name) => { a[name].user.push(user); }); return a; }, accum); console.log(output); 

Use Array.prototype.reduce() 使用Array.prototype.reduce()

 const receiver = { USER1: { module: ['a_critical', 'a_normal','b_normal'] }, USER2: { module: ['a_critical', 'a_normal','b_critical'] }, USER3: { module: ['a_critical'] } } const allModules = ['a_normal', 'a_critical', 'b_normal', 'b_critical'] const result = allModules.reduce((modulesObj, moduleName) => { modulesObj[moduleName] = [{ user: [] }] for (let user in receiver) { if (receiver[user].module.includes(moduleName)) { modulesObj[moduleName][0].user.push(user) } } return modulesObj }, {}) console.log(result) 

Try this one 试试这个

 const receiver = { USER1: { module: ['a_critical', 'a_normal','b_normal'] }, USER2: { module: ['a_critical', 'a_normal','b_critical'] }, USER3: { module: ['a_critical'] } }; const userByModules = Object.keys(receiver).reduce(function (acc, user) { receiver[user].module.forEach((module) => { if (acc[module]) { acc[module].user.push(user); } else { acc[module] = {user: [user]}; } }); return acc; }, {}); console.log(userByModules); 

const receiver = {
  USER1: {
    module: ["a_critical", "a_normal", "b_normal"]
  },
  USER2: {
    module: ["a_critical", "a_normal", "b_critical"]
  },
  USER3: {
    module: ["a_critical"]
  }
};

const allModules = ["a_normal", "a_critical", "b_normal", "b_critical"];

let reduce = () => {
  // create output object
  let output = {};

  // add modules into output
  allModules.map(mod => {
    return (output[mod] = [{ 'user': []}]);
  });

  // map users to modules
  for (let userKey in receiver) {
    let userModules = receiver[userKey].module;
    userModules.forEach(mod => {
      if(output.hasOwnProperty(mod)) {
        output[mod][0]['user'].push(userKey);
      }
    });
  }
};

reduce();

Straightforward way of getting the job done. 直接完成工作的方式。 No fancy functions used.Hopefully this logic would be easy to follow. 没有花哨的功能,希望这种逻辑很容易遵循。

The below snippet reduce the provided allModules array into the expected result. 下面的代码片段将提供的allModules数组allModules为预期的结果。 However, I think this structure 但是,我认为这种结构

"a_normal": {
      "user": [
        "USER1",
        "USER2"
      ]
 },
...

make sense more than the below snippet because you have to access the first index of each module to get user value 比下面的代码段更有意义,因为您必须访问每个模块的第一个索引以获得user价值

"a_normal": [
    {
      "user": [
        "USER1",
        "USER2"
      ]
    }
  ],

 const receiver = { USER1: { module: ["a_critical", "a_normal", "b_normal"] }, USER2: { module: ["a_critical", "a_normal", "b_critical"] }, USER3: { module: ["a_critical"] } }; const allModules = ["a_normal", "a_critical", "b_normal", "b_critical"]; const result = allModules.reduce((prevResult, curModule, index) => { if(!prevResult[curModule]) { prevResult[curModule]=[{user:[]}]; } Object.keys(receiver).forEach((user) => { if(receiver[user].module.includes(curModule) && !prevResult[curModule][0].user.includes(user)) { prevResult[curModule][0].user.push(user); } }); return prevResult; },{}); console.log(JSON.stringify(result, null, 2)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 结合Java中的Reduce和Map数据结构? - Combine a Reduce and Map Data Structure in Javascript? Javascript 将 object 的数组缩减为一个带键的 object - Javascript reduce array of object into one object with keys 将一个javascript嵌套对象数据结构转换为嵌套数组 - Convert one javascript nested object data structure to nested arrays How do I translate this map function from Javascript to Typescript given the structure of the data object being mapped? - How do I translate this map function from Javascript to Typescript given the structure of the data object being mapped? 基于给定数组减少 javascript object 中的键值对 - Reduce key value pairs in a javascript object based on a given array 如何将嵌套的JSON数据结构减少为映射JavaScript - How to reduce nested JSON data structure into a map JavaScript 如何在javascript中的给定数据范围内的每一天的每小时过滤一个数据object - How to filter one data object at each hour for each day in a given data range in javascript 将一种数据结构转换为另一种数据结构JavaScript / TypeScript - Transform one data structure into another data structure JavaScript/TypeScript Javascript使用这样的数据结构创建对象 - Javascript create object with data structure like this Javascript数据结构:面向对象还是数组? - Javascript data structure: Object oriented or array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM