【问题标题】:how to find a diff of object keys nested in array如何找到嵌套在数组中的对象键的差异
【发布时间】:2021-11-05 08:48:53
【问题描述】:

我有 3 个对象,它们有一个“成本”键,它是对象数组。结果,我想要一个“main”,它保持不变,除了它的“value”将是这个值减去其他对象“value”的差异

const main = {
  cost: [
    { id: 'main', value: 20, timestapm: 'asd', current: '10'},
    { id: 'main', value: 10, timestapm: 'asd', current: '10'},
    { id: 'main', value: 18, timestapm: 'asd', current: '10'},
  ],
  description: 'maindevice',
  total: 5
}

const other = {
  cost: [
    { id: 'device1', value: 10, timestapm: 'qwe', current: '10'},
    { id: 'device1', value: 5, timestapm: 'qwe', current: '10'},
    { id: 'device1', value: 9, timestapm: 'qwe', current: '10'},
  ],
  description: 'maindevice',
  total: 3
}

const other2 = {
  cost: [
    { id: 'device2', value: 5, timestapm: 'zxc', current: '10'},
    { id: 'device2', value: 2, timestapm: 'zxc', current: '10'},
    { id: 'device2', value: 2, timestapm: 'zxc', current: '10'},
  ],
  description: 'maindevice',
  total: 6
}

const devices = [main, other, other2];

result i want to have => 

main = {
  cost: [
    { id: 'main', value: 5, timestapm: 'asd', current: '10'},
    { id: 'main', value: 3, timestapm: 'asd', current: '10'},
    { id: 'main', value: 7, timestapm: 'asd', current: '10'},
  ],
  description: 'maindevice',
  total: 5
}

【问题讨论】:

  • 什么不起作用?
  • 我不知道该怎么做。我可以找到只有 3 个数组的差异,但是当这个数组嵌套在一个对象中时,我不知道该怎么做
  • 你想改变main吗?
  • @NinaScholz 是的,我可以改变它

标签: javascript arrays object


【解决方案1】:
const calcNewValue = (main, other, other2) => {
    main.cost = main.cost.map((obj, index) => { return {...obj, value: value=other.cost[index].value - other2.cost[index].value}})
    return main
}

这对你有用

【讨论】:

    【解决方案2】:

    您可以减少 devices 并改变数组的第一个对象。

    const
        main = { cost: [{ id: 'main', value: 20, timestamp: 'asd', current: '10'}, { id: 'main', value: 10, timestapm: 'asd', current: '10'}, { id: 'main', value: 18, timestapm: 'asd', current: '10'}], description: 'maindevice', total: 5 },
        other = { cost: [{ id: 'device1', value: 10, timestamp: 'qwe', current: '10'}, { id: 'device1', value: 5, timestapm: 'qwe', current: '10'}, { id: 'device1', value: 9, timestapm: 'qwe', current: '10'}], description: 'maindevice', total: 3 },
        other2 = { cost: [{ id: 'device2', value: 5, timestamp: 'zxc', current: '10'}, { id: 'device2', value: 2, timestapm: 'zxc', current: '10'}, { id: 'device2', value: 2, timestapm: 'zxc', current: '10'}], description: 'maindevice', total: 6 },
        devices = [main, other, other2];
    
    devices.reduce((r, o) => {
        o.cost.forEach(({ value }, i) => r.cost[i].value -= value);
        return r;
    });
    
    console.log(main);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      • 2015-10-23
      • 1970-01-01
      • 2021-11-30
      • 2015-02-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多