【问题标题】:Organizing Nested Object Data in JS?在 JS 中组织嵌套对象数据?
【发布时间】:2021-02-20 19:23:15
【问题描述】:

问题:

如何组织下例所示的“库存对象数据”,使其像下例所示的所需示例“结果”一样更有用?

仅限 ES6 方法。

示例数据:

const data = [
  { number: 1, desc: "I1", location: "L1", stock: 20 },
  { number: 2, desc: "I2", location: "L2", stock: 80 },
  { number: 3, desc: "I3", location: "L3", stock: 400 },
  { number: 1, desc: "I1", location: "L5", stock: 203 },
  { number: 1, desc: "I1", location: "L4", stock: 255 },
  { number: 2, desc: "I2", location: "L6", stock: 80 },
  { number: 2, desc: "I2", location: "L3", stock: 70 },
  { number: 3, desc: "I3", location: "L1", stock: 90 }
];

期望的结果:

const organizedList = {
  listName: "L1",
  items: [
    {
      number: 1,
      item: "I1",
      locations: [
        { loc: "L1", stock: 20 },
        { loc: "L5", stock: 203 },
        { loc: "L4", stock: 255 }
      ]
    },
    {
      number: 2,
      item: "I2",
      locations: [
        { loc: "L2", stock: 80 },
        { loc: "L6", stock: 80 },
        { loc: "L3", stock: 70 }
      ]
    },
    {
      number: 3,
      item: "I3",
      locations: [
        { loc: "L3", stock: 400 },
        { loc: "L1", stock: 90 }
      ]
    }
  ]
};

结果说明:

现在每个单独的项目都在列表中的单个对象中,而每个项目在其自己的对象数组中也有自己的位置和计数。

我的方法:

const dataNumbers = data.map((item) => {
  return item.number;
});

const uniqueNumbers = [...new Set(dataNumbers)];

console.log(uniqueNumbers);

function getAllIndexes(arr, val) {
  var indexes = [],
    i = -1;
  while ((i = arr.indexOf(val, i + 1)) != -1) {
    indexes.push(i);
  }
  return indexes;
}

const items = [];

const list = {
  listName: "test",
  items: items
};

for (let i = 0; i < uniqueNumbers.length; i++) {
  console.log(i);
  const indexes = getAllIndexes(dataNumbers, uniqueNumbers[i]);
  const indexedItem = data.filter((items) => {
    return items.number === uniqueNumbers[i];
  });

  const locations = indexedItem.map((item) => {
    const loc = item.location;
    const stock = item.stock;
    return { loc, stock };
  });
  const item = {
    number: uniqueNumbers[i],
    locations: locations
  };
  items.push(item);
}
console.log(list);

代码沙盒:https://codesandbox.io/s/funny-zhukovsky-xogp6?file=/src/index.js

我知道这是一项艰巨的任务,但任何有关缩短此代码的提示都将不胜感激。谢谢!

【问题讨论】:

    标签: javascript arrays reactjs object ecmascript-6


    【解决方案1】:

    可能的解决方案可能是一个 reduce 函数,例如:

    function organize (result, item, index, array) {
      if (!result.items) result.items = []
      if (!result.items[item.number]) {
        result.items[item.number] = {
          number: item.number,
          item: item.desc,
          locations: []
        }
      }
      result.items[item.number].locations.push({
        loc: item.location,
        stock: item.stock
      })
      if (array.length === index + 1) {
        result.items = Object.keys(result.items).map(i => result.items[i])
      }
      return result
    }
    

    用法:

    const myList = data.reduce(organize, { listName: 'L1' })
    

    注意事项:

    【讨论】:

    • 谢谢,比我的例子短得多,等我回到 15 级时,我会支持这个!
    【解决方案2】:

    这是一种解决方案,我们迭代数据并使用 findIndex 来查看是否有 item desc。如果找到索引,我们推送新位置,否则我们创建新项目。

    let items = []
    
    data.forEach(item =>{
        let index = items.findIndex(i => i.number===item.number)
        if(index>=0){
            items[index].locations.push({
                loc:item.location,
                stock:item.stock
            })
        }else{
            items.push({
                number:item.number,
                item:item.desc,
                locations:[{
                    loc:item.location,
                    stock:item.stock
                }]
            })
        }
    })
    
    const organizedList = {
        listName: "L1",
        items:items
    }
    
    console.log(organizedList)
    

    【讨论】:

    • 感谢您的回复!比我的尝试短得多。我会看看这个,希望能学到一些新东西!
    • 我喜欢你的方法,因为它很简单,我理解它,但如果我错了,请纠正我。首先,它遍历数据并将所有唯一项首先列出的数据推送到变量中。那么当 findIndex 函数看到一个重复的数字时,它会推入下一个位置键和值,直到不再出现?
    猜你喜欢
    • 2021-12-19
    • 1970-01-01
    • 2020-06-11
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-04
    相关资源
    最近更新 更多