合并具有相同日期的对象数组,但将动态属性添加到新数据结构中。

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

Merge array of objects when date is the same but add dynamic properties to new data structure

问题

以下是翻译好的部分:

我有以下代码

const measures = [
  { "13798494-value": 0.207, readingDate: "26/06/2023" },
  { "4958469-value": 0.211, readingDate: "26/06/2023" },
  { "13798494-value": 0.214, readingDate: "27/06/2023" },
  { "4958469-value": 0.123, readingDate: "27/06/2023" }
]

但我需要它像这样

const measures = [
    { readingDate: "26/06/2023", "13798494-value": 0.207, "4958469-value": 0.211 },
    { readingDate: "27/06/2023", "13798494-value": 0.214, "4958469-value": 0.123 }
]

我尝试了以下方法,但无法让它工作

 const reduceThis = measures?.reduce(
          (acc, item) => {
            const key = Object.keys(item)[0]
            const value = Object.values(item)[0]

            const queryResult = acc.find(
              (qr) => qr?.readingDate === item?.readingDate,
            )

            if (queryResult) {
              queryResult.results.push({ [key]: value })
            } else {
              let newQR = {
                readingDate: item?.readingDate,
                results: [{ [key]: value }],
              }
              acc.push(newQR)
            }

            return acc
          },
          [],
        )

但结果是

const measures = [
    { readingDate: "26/06/2023", results: [{"13798494-value": 0.207, "4958469-value": 0.211}] },
    { readingDate: "27/06/2023", results: [{"13798494-value": 0.214, "4958469-value": 0.123}] }
]

所以我差不多成功了,但还差一点。

格式 "XXXXXXXX-value" 是动态的,XXXXXXXX 可以是任何值,所以我们不能直接引用这些值。

谢谢


<details>
<summary>英文:</summary>

I have the following 

    const measures = [
      { &quot;13798494-value&quot;: 0.207, readingDate: &quot;26/06/2023&quot; },
      { &quot;4958469-value&quot;: 0.211 , readingDate: &quot;26/06/2023&quot; },
      { &quot;13798494-value&quot;: 0.214 , readingDate: &quot;27/06/2023&quot; },
      { &quot;4958469-value&quot;: 0.123, readingDate: &quot;27/06/2023&quot; }
    ]

but I need it like this 

    const measures = [
        { readingDate: &quot;26/06/2023&quot;, &quot;13798494-value&quot;: 0.207, &quot;4958469-value&quot;: 0.211 },
        { readingDate: &quot;27/06/2023&quot;, &quot;13798494-value&quot;: 0.214, &quot;4958469-value&quot;: 0.123 }
    ]

I&#39;ve tried the following but I cant get it to work 

```typescript

 const reduceThis = measures?.reduce(
          (acc, item) =&gt; {
            const key = Object.keys(item)[0]
            const value = Object.values(item)[0]

            const queryResult = acc.find(
              (qr) =&gt; qr?.readingDate === item?.readingDate,
            )

            if (queryResult) {
              queryResult.results.push({ [key]: value })
            } else {
              let newQR = {
                readingDate: item?.readingDate,
                results: [{ [key]: value }],
              }
              acc.push(newQR)
            }

            return acc
          },
          [],
        )

But this comes back as

const measures = [
    { readingDate: &quot;26/06/2023&quot;, results: [{&quot;13798494-value&quot;: 0.207, &quot;4958469-value&quot;: 0.211}] },
    { readingDate: &quot;27/06/2023&quot;, results: [{&quot;13798494-value&quot;: 0.214, &quot;4958469-value&quot;: 0.123}] }
]

So I'm nearly there but cant quite get it.

The format "XXXXXXXX-value" is dynamic and the XXXXXXXX can be anything so we cant directly reference those values.

Thanks

答案1

得分: 1

尝试这个

const measures = [
  { "13798494-value": 0.207, readingDate: "26/06/2023" },
  { "4958469-value": 0.211, readingDate: "26/06/2023" },
  { "13798494-value": 0.214, readingDate: "27/06/2023" },
  { "4958469-value": 0.123, readingDate: "27/06/2023" }
];

// 按 readingDate 分组测量值
const groupedMeasures = measures.reduce((acc, measure) => {
  const { readingDate, ...rest } = measure;
  if (!acc[readingDate]) {
    acc[readingDate] = { readingDate, ...rest };
  } else {
    Object.assign(acc[readingDate], rest);
  }
  return acc;
}, {});

// 将分组的测量值对象转换为数组
const sortedMeasures = Object.values(groupedMeasures);

以一个空对象 {} 开始 reduce。从当前索引获取 readingDate 并检查它是否已存在于对象中。如果是,将来自测量对象的剩余值 ...rest 添加到该日期。如果不是,将该日期添加为新键然后分配剩余值。然后转换为数组。

英文:

Try this

const measures = [
  { &quot;13798494-value&quot;: 0.207, readingDate: &quot;26/06/2023&quot; },
  { &quot;4958469-value&quot;: 0.211, readingDate: &quot;26/06/2023&quot; },
  { &quot;13798494-value&quot;: 0.214, readingDate: &quot;27/06/2023&quot; },
  { &quot;4958469-value&quot;: 0.123, readingDate: &quot;27/06/2023&quot; }
];

// Group the measures by readingDate
const groupedMeasures = measures.reduce((acc, measure) =&gt; {
  const { readingDate, ...rest } = measure;
  if (!acc[readingDate]) {
    acc[readingDate] = { readingDate, ...rest };
  } else {
    Object.assign(acc[readingDate], rest);
  }
  return acc;
}, {});

// Convert the grouped measures object to an array
const sortedMeasures = Object.values(groupedMeasures);

Start reduce with an empty object {}. Get readingDate from current index and check if it already exists in the object. If yes, add the remaining values ...rest from the measures object for the date. If not, add the date as a new key and assign remaining values then. Convert to an array afterwards.

答案2

得分: 1

为了提高速度,可以使用 Array::reduce 来收集具有相同 readingDate 的项目,并将其存储在数组和映射中(以便进一步快速访问以添加其他属性):

const measures = [
  { "13798494-value": 0.207, readingDate: "26/06/2023" },
  { "4958469-value": 0.211 , readingDate: "26/06/2023" },
  { "13798494-value": 0.214 , readingDate: "27/06/2023" },
  { "4958469-value": 0.123, readingDate: "27/06/2023" }
]

const mapped = measures.reduce((r, {readingDate, ...props}) => {
  let item = r.map.get(readingDate);
  item ? Object.assign(item, props) :
    r.map.set(readingDate, r.arr[r.arr.length] = {readingDate, ...props});
  return r;
}, {arr: [], map: new Map}).arr;

console.log(mapped);

请注意,上述代码段已被翻译,如您所需。

英文:

To make it fast use Array::reduce to collect items with the same readingDate in an array and in a map (for further quick access to add additional properties):

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

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

const measures = [
  { &quot;13798494-value&quot;: 0.207, readingDate: &quot;26/06/2023&quot; },
  { &quot;4958469-value&quot;: 0.211 , readingDate: &quot;26/06/2023&quot; },
  { &quot;13798494-value&quot;: 0.214 , readingDate: &quot;27/06/2023&quot; },
  { &quot;4958469-value&quot;: 0.123, readingDate: &quot;27/06/2023&quot; }
]

  
const mapped = measures.reduce((r, {readingDate, ...props}) =&gt; {
  let item = r.map.get(readingDate);
  item ? Object.assign(item, props) :
    r.map.set(readingDate, r.arr[r.arr.length] = {readingDate, ...props});
  return r;
}, {arr: [], map: new Map}).arr;

console.log(mapped);

<!-- end snippet -->

答案3

得分: 1

你可以逐个项地减少对象数组以构建一个新的数组。在迭代过程中,如果当前对象在新数组中不存在,就将其添加,否则,将当前对象的内容展开到现有对象中。

const measures = [
    { "13798494-value": 0.207, readingDate: "26/06/2023" },
    { "4958469-value": 0.211 , readingDate: "26/06/2023" },
    { "13798494-value": 0.214 , readingDate: "27/06/2023" },
    { "4958469-value": 0.123, readingDate: "27/06/2023" }
]

const reduced = measures.reduce((acc, cur) => {
    const foundIndex = acc.findIndex(({ readingDate }) => (readingDate === cur.readingDate));
    if (foundIndex > -1)
        acc[foundIndex] = { ...acc[foundIndex], ...cur };
    else
        acc.push(cur);
    return acc;
}, []);

console.log(reduced);
英文:

You can reduce the array of object to build a new one item by item. As you iterate, if the current object does not exist in the new one, you add it, otherwise, you spread the contents of the current object into the existing one.

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

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

const measures = [
    { &quot;13798494-value&quot;: 0.207, readingDate: &quot;26/06/2023&quot; },
    { &quot;4958469-value&quot;: 0.211 , readingDate: &quot;26/06/2023&quot; },
    { &quot;13798494-value&quot;: 0.214 , readingDate: &quot;27/06/2023&quot; },
    { &quot;4958469-value&quot;: 0.123, readingDate: &quot;27/06/2023&quot; }
]

const reduced = measures.reduce((acc, cur) =&gt; {
    const foundIndex = acc.findIndex(({ readingDate }) =&gt; (readingDate === cur.readingDate));
    if (foundIndex &gt; -1)
        acc[foundIndex] = { ...acc[foundIndex], ...cur };
    else
        acc.push(cur);
    return acc;
}, []);

console.log(reduced);

<!-- end snippet -->

答案4

得分: 1

这可以合并,但在我看来更容易阅读

let grouped = measures.reduce((acc, cur) => {
  const { readingDate, ...rest } = cur;
  acc[readingDate] ??= { results: [] }; // 在需要时初始化
  acc[readingDate].results.push(rest); // 添加
  return acc;
}, {});
grouped = Object.entries(grouped).reduce((acc, [key, value]) => {
  acc.push({ readingDate: key, results: value.results });
  return acc;
}, []);
console.log(grouped)
<script>
const measures = [
  { "13798494-value": 0.207, readingDate: "26/06/2023" },
  { "4958469-value": 0.211 , readingDate: "26/06/2023" },
  { "13798494-value": 0.214 , readingDate: "27/06/2023" },
  { "4958469-value": 0.123, readingDate: "27/06/2023" }
]
</script>
英文:

This could be consolidated but is in my opinion easier to read

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

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

let grouped = measures.reduce((acc, cur) =&gt; {
  const { readingDate, ...rest } = cur;
  acc[readingDate] ??= { results: [] }; // initialise when needed
  acc[readingDate].results.push(rest); // add
  return acc;
}, {});
grouped = Object.entries(grouped).reduce((acc, [key, value]) =&gt; {
  acc.push({ readingDate: key, results: value.results });
  return acc;
}, []);
console.log(grouped)

<!-- language: lang-html -->

&lt;script&gt;
const measures = [
  { &quot;13798494-value&quot;: 0.207, readingDate: &quot;26/06/2023&quot; },
  { &quot;4958469-value&quot;: 0.211 , readingDate: &quot;26/06/2023&quot; },
  { &quot;13798494-value&quot;: 0.214 , readingDate: &quot;27/06/2023&quot; },
  { &quot;4958469-value&quot;: 0.123, readingDate: &quot;27/06/2023&quot; }
]
&lt;/script&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月10日 22:30:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76654764.html
匿名

发表评论

匿名网友

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

确定