有没有一种方法可以重新排列数组中的对象,使值成为键?

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

Is there way to rearange objects in array that the value becomes the key?

问题

以下是您要的翻译:

"I'm stuck on this type of situation where the values of the object is changed to a different value. Is there way to shift a value to a key or would simply deleting and adding be better? I tried to loop to see which of the keys overlap in value and using the if statement and conditions i tried adding or deleting using Array methods. However, since the inter data is an object i am sruggling to find the right methods or even the process. I also tried using a function to insert the data and pushing to a new empty array that is returned from the function."

我卡在这种情况下,其中对象的值被更改为不同的值。是否有一种将值转移到键的方法,还是简单地删除和添加更好?我尝试循环查看哪些键重叠在值上,并使用if语句和条件尝试使用数组方法进行添加或删除。但是,由于inter data是一个对象,我很难找到正确的方法甚至是过程。我还尝试使用一个函数来插入数据并将其推送到从函数返回的新空数组中。

"If I have objects in an array like so:"

如果我有这样的数组中的对象:

{
    "date": "12/22",
    "treatment": "nausea",
    "count": 2
},
{
    "date": "12/23",
    "treatment": "cold",
    "count": 3
},
{
    "date": "12/22",
    "treatment": "cold",
    "count": 2
}
];```

and wanting to change the data like so:

并且希望将数据更改如下:

```const newData = [
{
    "date": "12/22",
    "cold": 2,
    "nausea": 2,
},
{
    "date": "12/23",
    "cold": 3
}
];```

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

I&#39;m stuck on this type of situation where the values of the object is changed to a different value. Is there way to shift a value to a key or would simply deleting and adding be better? I tried to loop to see which of the keys overlap in value and using the if statement and conditions i tried adding or deleting using Array methods. However, since the inter data is an object i am sruggling to find the right methods or even the process. I also tried using a function to insert the data and pushing to a new empty array that is returned from the function.

If I have objects in an array like so:

const data = [
{
"date": "12/22",
"treatment": "nausea",
"count": 2
},
{
"date": "12/23",
"treatment": "cold",
"count": 3
},
{
"date": "12/22",
"treatment": "cold",
"count": 2
}
];

and wanting to change the data like so:

const newData = [
{
"date": "12/22",
"cold": 2
"nausea": 2,
},
{
"date": "12/23",
"cold": 3
}
];


</details>


# 答案1
**得分**: 1

尝试使用循环和减少(reduce)并每次添加到新数组的代码:

```js
const data = [
    {
        "date": "12/22",
        "treatment": "nausea",
        "count": 2
    },
    {
        "date": "12/23",
        "treatment": "cold",
        "count": 3
    },
    {
        "date": "12/22",
        "treatment": "cold",
        "count": 2
    }
];

const newData = [];
const dataByDate = data.reduce((acc, curr) => {
    if (!acc[curr.date]) {
        acc[curr.date] = { date: curr.date };
    }
    acc[curr.date][curr.treatment] = curr.count;
    return acc;
}, {});

for (let date in dataByDate) {
    newData.push(dataByDate[date]);
}

console.log(newData);

这段代码会将原始数据按照日期和治疗方式进行汇总,并将结果存储在新数组 newData 中。

英文:

try this code using loop and reduce and every time add to new array
<!-- begin snippet: js hide: false console: true babel: false -->

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

const data = [
{
    &quot;date&quot;: &quot;12/22&quot;,
    &quot;treatment&quot;: &quot;nausea&quot;,
    &quot;count&quot;: 2
},
{
    &quot;date&quot;: &quot;12/23&quot;,
    &quot;treatment&quot;: &quot;cold&quot;,
    &quot;count&quot;: 3
},
{
    &quot;date&quot;: &quot;12/22&quot;,
    &quot;treatment&quot;: &quot;cold&quot;,
    &quot;count&quot;: 2
}
];

const newData = [];
const dataByDate = data.reduce((acc, curr) =&gt; {
    if (!acc[curr.date]) {
        acc[curr.date] = { date: curr.date };
    }
    acc[curr.date][curr.treatment] = curr.count;
    return acc;
}, {});

for (let date in dataByDate) {
    newData.push(dataByDate[date]);
}

console.log(newData);

<!-- end snippet -->

答案2

得分: 1

以下是翻译好的内容:

We want to reduce the data by unique dates. This can be done with:

Prefer to use Array.reduce() when reducing an array. This is standardized and more expressive than a custom implementation.

Using a map-like structure as the accumulator allows reduction of the dates by uniqueness and the data itself, simultaneously.

Note: Properties of objects are converted to Strings (except for Symbols). So if you want to use different "keys" that are equal after conversion (e.g. 0 and "0"), you cannot use objects; use Map instead.
(All our dates are Strings already, so this warning does not apply here.)

When using an object we can use the nullish coalescing assignment ??=: This allows us to assign an initial "empty" entry ({ date: dataEntry.date }) when encountering a new unique date.

Further, that assignment evaluates to the dictionary's entry; the entry that was either already present or just assigned.

const data = [
  { "date": "12/22", "treatment": "nausea", "count": 2 },
  { "date": "12/23", "treatment": "cold", "count": 3 },
  { "date": "12/22", "treatment": "cold", "count": 2 }
];

const newData = reduceByDate(data);
console.log(newData);

function reduceByDate(data) {
  const dataByDate = data.reduce((dict, dataEntry) => {
    const dictEntry = dict[dataEntry.date] // Get existing or ...
      ??= { date: dataEntry.date }; // ... just initialized entry.
    
    dictEntry[dataEntry.treatment] = dataEntry.count;
    return dict;
  }, {});
  
  // Transform dictionary to array of reduced entries
  return Object.values(dataByDate);
}
英文:

We want to reduce the data by unique dates. This can be done with:

Prefer to use Array.reduce() when reducing an array. This is standardized and more expressive than a custom implementation.

Using a map-like structure as the accumulator allows reduction of the dates by uniqueness and the data itself, simultaneously.

Note: Properties of objects are converted to Strings (except for Symbols). So if you want to use different "keys" that are equal after conversion (e.g. 0 and &quot;0&quot;), you cannot use objects; use Map instead.
(All our dates are Strings already, so this warning does not apply here.)

When using an object we can use the nullish coalescing assignment ??=: This allows us to assign an initial "empty" entry ({ date: dataEntry.date }) when encountering a new unique date.

Further, that assignment evaluates to the dictionary's entry; the entry that was either already present or just assigned.

Then we only need to assign the treatment and its count as a key-value pair to the entry.

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

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

const data = [
  { &quot;date&quot;: &quot;12/22&quot;, &quot;treatment&quot;: &quot;nausea&quot;, &quot;count&quot;: 2 },
  { &quot;date&quot;: &quot;12/23&quot;, &quot;treatment&quot;: &quot;cold&quot;, &quot;count&quot;: 3 },
  { &quot;date&quot;: &quot;12/22&quot;, &quot;treatment&quot;: &quot;cold&quot;, &quot;count&quot;: 2 }
];

const newData = reduceByDate(data);
console.log(newData);

function reduceByDate(data) {
  const dataByDate = data.reduce((dict, dataEntry) =&gt; {
    const dictEntry = dict[dataEntry.date] // Get existing or ...
      ??= { date: dataEntry.date }; // ... just initialized entry.
    
    dictEntry[dataEntry.treatment] = dataEntry.count;
    return dict;
  }, {});
  
  // Transform dictionary to array of reduced entries
  return Object.values(dataByDate);
}

<!-- end snippet -->

答案3

得分: 0

你可以使用reduce()Object.assign()。首先,我们使用reduce将具有相同日期的对象合并为一个对象,然后使用assign来合并值:

const data = [{
    "date": "12/22",
    "treatment": "nausea",
    "count": 2
  },
  {
    "date": "12/23",
    "treatment": "cold",
    "count": 3
  },
  {
    "date": "12/22",
    "treatment": "cold",
    "count": 2
  }
];

const newData = data.reduce((acc, curr) => {
  const dateIndex = acc.findIndex(item => item.date === curr.date);
  if (dateIndex === -1) {
    acc.push({
      date: curr.date,
      [curr.treatment]: curr.count
    });
  } else {
    acc[dateIndex] = Object.assign({}, acc[dateIndex], {
      [curr.treatment]: curr.count
    });
  }
  return acc;
});

console.log(newData)
英文:

You can make use of reduce() and Object.assign().
First we use reduce to combine objects with the same date into one object and then use assign to merge the values:

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

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

const data = [{
    &quot;date&quot;: &quot;12/22&quot;,
    &quot;treatment&quot;: &quot;nausea&quot;,
    &quot;count&quot;: 2
  },
  {
    &quot;date&quot;: &quot;12/23&quot;,
    &quot;treatment&quot;: &quot;cold&quot;,
    &quot;count&quot;: 3
  },
  {
    &quot;date&quot;: &quot;12/22&quot;,
    &quot;treatment&quot;: &quot;cold&quot;,
    &quot;count&quot;: 2
  }
];

const newData = data.reduce((acc, curr) =&gt; {
  const dateIndex = acc.findIndex(item =&gt; item.date === curr.date);
  if (dateIndex === -1) {
    acc.push({
      date: curr.date,
      [curr.treatment]: curr.count
    });
  } else {
    acc[dateIndex] = Object.assign({}, acc[dateIndex], {
      [curr.treatment]: curr.count
    });
  }
  return acc;
}, []);

console.log(newData)

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月8日 15:44:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75382660.html
匿名

发表评论

匿名网友

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

确定