【问题标题】:JavaScript - Dynamically update array of nested objects from another array of nested objectsJavaScript - 从另一个嵌套对象数组动态更新嵌套对象数组
【发布时间】:2021-11-17 00:03:38
【问题描述】:

我正在根据另一个数组中的对象从数组中添加、更新或删除嵌套对象。例如,我想根据update 数组更新date -> gte 的值,同时保留entry -> eq 并添加date -> lte

我已尝试使用以下 sn-p,但结果会产生带有错误键/值的夸大结果。

const existing = [
  { date: { gte: '2021-01-01' } },
  { entry: { eq: 1 } },
  { keep: { eq: 100 } },
];
const update = [
  { date: { gte: '2021-02-01' } },
  { date: { lte: '2021-12-31' } },
];

const outcome = [];

update.forEach((el) => {
  existing.forEach(elem => {
    Object.entries(elem).forEach(([k, v]) => {
      Object.entries(el).forEach(([key, value]) => {
        if (k === key && Object.keys(v).sort().toString() === Object.keys(value).sort().toString()) {
          outcome.push(el)
        } else {
          outcome.push(elem)
        }
      });
    });
  })
});

console.log(outcome);

// expected outcome
// [
//   { date: { gte: '2021-02-01' } }, 
//   { entry: { eq: 1 }},
//   { keep: { eq: 100 } },
//   { date: { lte: '2021-12-31' } }
// ]

// current outcome 
// [
//   { date: { gte: '2021-02-01' } },
//   { entry: { eq: 1 } },
//   { keep: { eq: 100 } },
//   { date: { gte: '2021-01-01' } },
//   { entry: { eq: 1 } },
//   { keep: { eq: 100 } }
// ]

【问题讨论】:

  • 请向我们提供Minimal, Reproducible Example,最好使用工作代码sn-p
  • 我添加了一个包含更多信息的可重现示例。
  • 当您使用Object.keys().sort() 时,您没有选择特定索引。你应该吗?我希望您在使用 toString() 之前可能需要这样做。

标签: javascript arrays object


【解决方案1】:

这对于您的情况应该足够了(就地更新):

const existing = [
  { date: { gte: '2021-01-01' } },
  { entry: { eq: 1 } },
  { keep: { eq: 100 } },
];
const update = [
  { date: { gte: '2021-02-01' } },
  { date: { lte: '2021-12-31' } },
];

while (update.length) {
  const u = update.shift();
  const [p, o] = Object.entries(u)[0];  
  const [k, v] = Object.entries(o)[0];
  const f = existing.find(e => p in e && k in e[p]);
  f ? f[p][k] = v : existing.push(u);
}

console.log(existing);

【讨论】:

    猜你喜欢
    • 2021-11-27
    • 1970-01-01
    • 2021-09-03
    • 2021-07-27
    • 1970-01-01
    • 2021-06-07
    • 2020-07-11
    • 2020-12-21
    • 1970-01-01
    相关资源
    最近更新 更多