JavaScript高级数组操作

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

Javascript Advanced Array Manipulation

问题

以下是代码的翻译部分:

给定一个截断的对象数组

```const catsData = [
    {
        emotionTags: ["moody"],
        isGif: false,
        image: "angry.jpeg",
        alt: "A cat looking moody",
    },
    {
        emotionTags: ["moody", "insomniac"],
        isGif: false,
        image: "angry2.jpeg",
        alt: "A cat looking moody",
    },
    {
        emotionTags: ["moody"],
        isGif: false,
        image: "angry3.jpeg",
        alt: "A cat looking moody",
    },
    {
        emotionTags: ["confused", "sad"],
        isGif: false,
        image: "confused.jpeg",
        alt: "A cat looking confused",
    }]

我希望将它转换成如下的数组:

    {
        emotionTags: 'moody',
        isGif: false,
        image: ["angry.jpeg", 'angry2.jpeg','angry3.jpeg', 'sad1.jpeg'],
        alt: ['A cat looking moody', 'A cat looking sad']
    },
    {
        emotionTags: 'insomniac',
        isGif: false,
        image: ['angry2.jpeg', 'insomnia.jpeg', 'insomnia1.jpeg'],
        alt: ['A cat looking moody', 'A cat looking insomniac',]
    },
    {
        emotionTags: 'confused',
        isGif: false,
        image: ['confused.jpeg'],
        alt: ['A cat looking confused']
    }
]

使得与特定情绪相对应的所有图像都分组在图像数组中(如果可能的话,也分组在其alt中)。与多个情绪相关联的图像也可以分组在该情绪的对象中。

我尝试了以下操作:

let emotions = ['moody','insomniac','confused','sad','dominant','hungry','relaxed','angry']

let modCatData = catsData.reduce((allCat, cat, idx) => {
  let imageArr = []
  if (cat['emotionTags'].includes(emotions[idx])) {
    imageArr.push(cat.image)
    allCat.push({
      'image': imageArr
    })
  }
  else {
    allCat.push({
      'image': cat.image
    })
  }
  return allCat
  
},[])

console.log(modCatData)

我希望能够选择一种情绪,将其与对象中的情感进行比较,并将与之对应的图像分组,但到目前为止,我很难分组图像。

如果可能的话,会很感激提供解决方案或方向。

英文:

Given a truncated array of object

const catsData = [
    {
        emotionTags: ["moody"],
        isGif: false,
        image: "angry.jpeg",
        alt: "A cat looking moody",
    },
    {
        emotionTags: ["moody", "insomniac"],
        isGif: false,
        image: "angry2.jpeg",
        alt: "A cat looking moody",
    },
    {
        emotionTags: ["moody"],
        isGif: false,
        image: "angry3.jpeg",
        alt: "A cat looking moody",
    },
    {
        emotionTags: ["confused", "sad"],
        isGif: false,
        image: "confused.jpeg",
        alt: "A cat looking confused",
    }]

I would love to transform it into an array like below:

    {
        emotionTags: 'moody',
        isGif: false,
        image: ["angry.jpeg", 'angry2.jpeg','angry3.jpeg', 'sad1.jpeg'],
        alt: ['A cat looking moody', 'A cat looking sad']
    },
    {
        emotionTags: 'insomniac',
        isGif: false,
        image: ['angry2.jpeg', 'insomnia.jpeg', 'insomnia1.jpeg'],
        alt: ['A cat looking moody', 'A cat looking insomniac',]
    },
    {
        emotionTags: 'confused',
        isGif: false,
        image: ['confused.jpeg'],
        alt: ['A cat looking confused']
    }
]

Such that all images that corresponds to a particular mood are grouped in an array of images (same with their alt if possible). images that correspond to more than one mood can also be grouped in that particular's mood object too.

I tried doing the below:

 let emotions = ['moody','insomniac','confused','sad','dominant','hungry','relaxed','angry']

 let modCatData = catsData.reduce((allCat, cat,idx)=>{
  let imageArr = []
  if(cat['emotionTags'].includes (emotions[idx])){
    imageArr.push(cat.image)
    allCat.push({
      'image':imageArr
    })
  }
  else{
    allCat.push({
      'image':cat.image
    })
  }
  return allCat
  
},[])

console.log(modCatData)ere

I was hoping to be able to pick an emotion, test it against the object emotions, and grouped the images that correspond with it, but i have difficulty grouping the images so far.

would appreciate a solution or direction if possible.

答案1

得分: 1

以下是翻译好的部分:

"Firstly, the input you provided has no sentences like, "A cat looking insomniac" or "A cat looking sad" but your output includes those sentences. So, not sure what is your correct data."

"Second, if I got your question correctly then you want to create an array of moods and group the images and alts of that particular mood in that single mood item. So you might try the following-"

"1. Run loop on mood array."
"2. Filter which items are having the current mood."
"3. Get the images and alts from the filtered items using the map function."
"4. I used the Set operator to filter the unique images and alt in case of duplicity."

"Here is the demo-"

"const catsData = ["
" {"
" emotionTags: ['moody'],"
" isGif: false,"
" image: 'angry.jpeg',"
" alt: 'A cat looking moody',"
" },"
" {"
" emotionTags: ['moody', 'insomniac'],"
" isGif: false,"
" image: 'angry2.jpeg',"
" alt: 'A cat looking moody',"
" },"
" {"
" emotionTags: ['moody'],"
" isGif: false,"
" image: 'angry3.jpeg',"
" alt: 'A cat looking moody',"
" },"
" {"
" emotionTags: ['confused', 'sad'],"
" isGif: false,"
" image: 'confused.jpeg',"
" alt: 'A cat looking confused',"
" }"
" ];"

"let emotions = ['moody', 'insomniac', 'confused', 'sad', 'dominant', 'hungry', 'relaxed', 'angry']"

"let final = [];"

"emotions.forEach(e => {"
" let obj = {}"
" let result = catsData.filter(cd => cd.emotionTags.includes(e))"
" obj.emotionTags = e;"
" obj.isGif = false;"
" obj.image = [...new Set(result.map(item => item.image))]"
" obj.alt = [...new Set(result.map(item => item.alt))]"
" final.push(obj)"
"})"

"console.log(final)"

英文:

Firstly, the input you provided has no sentences like, "A cat looking insomniac" or "A cat looking sad" but your output includes those sentences. So, not sure what is your correct data.

Second, if I got your question correctly then you want to create an array of moods and group the images and alts of that particular mood in that single mood item. So you might try the following-

  1. Run loop on mood array.
  2. Filter which items are having the current mood.
  3. Get the images and alts from the filtered items using the map function.
  4. I used the Set operator to filter the unique images and alt in case of duplicity.

Here is the demo-

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

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

const catsData = [{
    emotionTags: [&quot;moody&quot;],
    isGif: false,
    image: &quot;angry.jpeg&quot;,
    alt: &quot;A cat looking moody&quot;,
  },
  {
    emotionTags: [&quot;moody&quot;, &quot;insomniac&quot;],
    isGif: false,
    image: &quot;angry2.jpeg&quot;,
    alt: &quot;A cat looking moody&quot;,
  },
  {
    emotionTags: [&quot;moody&quot;],
    isGif: false,
    image: &quot;angry3.jpeg&quot;,
    alt: &quot;A cat looking moody&quot;,
  },
  {
    emotionTags: [&quot;confused&quot;, &quot;sad&quot;],
    isGif: false,
    image: &quot;confused.jpeg&quot;,
    alt: &quot;A cat looking confused&quot;,
  }
];

let emotions = [&#39;moody&#39;, &#39;insomniac&#39;, &#39;confused&#39;, &#39;sad&#39;, &#39;dominant&#39;, &#39;hungry&#39;, &#39;relaxed&#39;, &#39;angry&#39;]

let final = [];

emotions.forEach(e =&gt; {
  let obj = {}
  let result = catsData.filter(cd =&gt; cd.emotionTags.includes(e))
  obj.emotionTags = e;
  obj.isGif = false;
  obj.image = [...new Set(result.map(item =&gt; item.image))]
  obj.alt = [...new Set(result.map(item =&gt; item.alt))]
  final.push(obj)
})

console.log(final)

<!-- end snippet -->

Let me know if your data is something different, I will update the answer.

答案2

得分: 0

这是一种使用.reduce()调用源数组进行分组的方法。然后,你可以过滤结果以找到特定的情感。

const catsData = [
  {
    emotionTags: ['moody'],
    isGif: false,
    image: 'angry.jpeg',
    alt: 'A cat looking moody',
  },
  {
    emotionTags: ['moody', 'insomniac'],
    isGif: false,
    image: 'angry2.jpeg',
    alt: 'A cat looking moody',
  },
  {
    emotionTags: ['moody'],
    isGif: false,
    image: 'angry3.jpeg',
    alt: 'A cat looking moody',
  },
  {
    emotionTags: ['confused', 'sad'],
    isGif: false,
    image: 'confused.jpeg',
    alt: 'A cat looking confused',
  },
];

const modified = catsData.reduce((aggregate, item) => {
  for (var emotion of item.emotionTags) {
    let existing = aggregate.find((i) => i.emotionTags === emotion);
    if (!existing) {
      aggregate.push((existing = { emotionTags: emotion, isGif: item.isGif, image: [], alt: [] }));
    }
    existing.image = [...new Set([...existing.image, item.image])]; // Trim to distinct values
    existing.alt = [...new Set([...existing.alt, item.alt])]; // Trim to distinct values
  }
  return aggregate;
}, []);

console.log(modified);
英文:

Here is a way to do the grouping using a .reduce() call on the source array. Then you can just filter the result to a specific emotion you are looking for.

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

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

const catsData = [
  {
    emotionTags: [&#39;moody&#39;],
    isGif: false,
    image: &#39;angry.jpeg&#39;,
    alt: &#39;A cat looking moody&#39;,
  },
  {
    emotionTags: [&#39;moody&#39;, &#39;insomniac&#39;],
    isGif: false,
    image: &#39;angry2.jpeg&#39;,
    alt: &#39;A cat looking moody&#39;,
  },
  {
    emotionTags: [&#39;moody&#39;],
    isGif: false,
    image: &#39;angry3.jpeg&#39;,
    alt: &#39;A cat looking moody&#39;,
  },
  {
    emotionTags: [&#39;confused&#39;, &#39;sad&#39;],
    isGif: false,
    image: &#39;confused.jpeg&#39;,
    alt: &#39;A cat looking confused&#39;,
  },
];

const modified = catsData.reduce((aggregate, item) =&gt; {
  for (var emotion of item.emotionTags) {
    let existing = aggregate.find((i) =&gt; i.emotionTags === emotion);
    if (!existing) {
      aggregate.push((existing = { emotionTags: emotion, isGif: item.isGif, image: [], alt: [] }));
    }
    existing.image = [...new Set([...existing.image, item.image])]; // Trim to distinct values
    existing.alt = [...new Set([...existing.alt, item.alt])]; // Trim to distinct values
  }
  return aggregate;
}, []);

console.log(modified);

<!-- end snippet -->

答案3

得分: 0

你可以使用对象来进行分组。

英文:

You could use an object for grouping.

<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const
addIfNotExist = (array, value) => {
if (!array.includes(value)) array.push(value);
},
data = [{ emotionTags: ["moody"], isGif: false, image: "angry.jpeg", alt: "A cat looking moody" }, { emotionTags: ["moody", "insomniac"], isGif: false, image: "angry2.jpeg", alt: "A cat looking moody" }, { emotionTags: ["moody"], isGif: false, image: "angry3.jpeg", alt: "A cat looking moody" }, { emotionTags: ["confused", "sad"], isGif: false, image: "confused.jpeg", alt: "A cat looking confused" }],
result = Object.values(data.reduce((r, { emotionTags, isGif, ...o }) => {
emotionTags.forEach(emotionTag => {
r[emotionTag] ??= { emotionTag, isGif, image: [], alt: [] };
['image', 'alt'].forEach(k => addIfNotExist(r[emotionTag][k], o[k]));
});
return r;
}, {}));

console.log(result);

<!-- language: lang-css -->
.as-console-wrapper { max-height: 100% !important; top: 0; }
<!-- end snippet -->

答案4

得分: 0

这里无需硬编码情感。您可以使用一个简单的 .reduce()。尝试这个:

const catsData = [{emotionTags: ["moody"], isGif: false, image: "angry.jpeg", alt: "A cat looking moody", }, {emotionTags: ["moody", "insomniac"], isGif: false, image: "angry2.jpeg", alt: "A cat looking moody", }, {emotionTags: ["moody"], isGif: false, image: "angry3.jpeg", alt: "A cat looking moody", }, {emotionTags: ["confused", "sad"], isGif: false, image: "confused.jpeg", alt: "A cat looking confused", } ];

const result = catsData.reduce((acc, o) => {
    o.emotionTags.forEach(tag => {
        let item = acc.find(i => i.emotionTags === tag) ?? { emotionTags: tag, isGif: o.isGif, image: [], alt: [] };
        if (!item.image.length) acc.push(item);
        item.image.push(o.image);
        item.alt.push(o.alt);
    });

    return acc;
});

console.log(result);

这是给定代码的翻译部分。

英文:

There is no need to hard code the emotions. You can use a simple .reduce(). Try this

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

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

const catsData = [{emotionTags: [&quot;moody&quot;], isGif: false, image: &quot;angry.jpeg&quot;, alt: &quot;A cat looking moody&quot;, }, {emotionTags: [&quot;moody&quot;, &quot;insomniac&quot;], isGif: false, image: &quot;angry2.jpeg&quot;, alt: &quot;A cat looking moody&quot;, }, {emotionTags: [&quot;moody&quot;], isGif: false, image: &quot;angry3.jpeg&quot;, alt: &quot;A cat looking moody&quot;, }, {emotionTags: [&quot;confused&quot;, &quot;sad&quot;], isGif: false, image: &quot;confused.jpeg&quot;, alt: &quot;A cat looking confused&quot;, } ];

const result = catsData.reduce((acc, o) =&gt; {
    o.emotionTags.forEach(tag =&gt; {
        let item = acc.find(i =&gt; i.emotionTags === tag) ?? { emotionTags: tag, isGif: o.isGif, image: [], alt: [] };
        if (!item.image.length) acc.push(item);
        item.image.push(o.image);
        item.alt.push(o.alt);
    });

    return acc;
}, []);

console.log(result);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月3日 19:43:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75626655.html
匿名

发表评论

匿名网友

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

确定