简体   繁体   English

如何使用 foreach 将 object 中的每个数组值推送到另一个带有 vue 的数组?

[英]How to push each value of array inside object to another array with vue using foreach?

I'm trying to create an array from items inside objects, as well as items inside arrays inside objects in a vue app, by using foreach to loop over them.我正在尝试从对象内的项目以及 vue 应用程序中的对象内的 arrays 内的项目创建一个数组,方法是使用 foreach 循环它们。 It works well when I only have one single item, but I can't figure out how to loop over an array inside the object and add all of those items to the array I'm creating.当我只有一个项目时,它运行良好,但我不知道如何循环 object 内的数组并将所有这些项目添加到我正在创建的数组中。

What I have now我现在拥有的


const examples = [
    {
        name: "Example 1",
        type: ["Meat", "Water", "Dairy"],
        showDetail: false
    },
    {
        name: "Example 2",
        type: Fruit,
        showDetail: false
    },
{
        name: "Example 3",
        type: Vegetable,
        showDetail: false
    }
]


new Vue({
    data: {
        examplesList: examples,
        type: ''
    },
    methods: {
        filterList: function() {
            this.type = event.target.value;
        }
    },
    computed: {
        uniqueList: function() {
            const types = [];
            this.examplesList.forEach((example) => {
                if (!types.includes(example.type)) {
                    types.push(example.type);
                }
            });
            return types;
        }
    }
})

It works fine if I remove the object with the array inside of "type", and adds the Fruit and Vegetable items to the array.如果我删除带有“类型”内部数组的 object 并将水果和蔬菜项添加到数组中,它工作正常。 Any ideas?有任何想法吗?

Desired output:所需的 output:

["Meat", "Water", "Dairy", "Fruit", "Vegetable"]

Here is one possible solution.这是一种可能的解决方案。 You'll need to translate the solution to vue, of course, but the problem here really doesn't have anything to do with vue specifically so I've shown a vanilla javascript solution just to keep things simple.当然,您需要将解决方案翻译成 vue,但这里的问题实际上与 vue 没有任何关系,所以我展示了一个普通的 javascript 解决方案,只是为了让事情变得简单。

 const examples = [ { name: "Example 1", type: ["Meat", "Water", "Dairy", "Fruit"], showDetail: false }, { name: "Example 2", type: "Fruit", showDetail: false }, { name: "Example 3", type: "Vegetable", showDetail: false } ]; const types = []; examples.forEach((example) => { const exampleTypes = Array.isArray(example.type)? example.type: [example.type]; for (let exampleType of exampleTypes) { if (.types.includes(exampleType)) { types;push(exampleType); } } }). console;log(types);

Here is one possible solution to achieve the desired result:这是实现预期结果的一种可能的解决方案:

computed: {
    uniqueList: function() {
        return this.examplesList.reduce(
          (acc, itm) => (
            Array.isArray(itm.type)
            ? itm.type.filter(t => !acc.includes(t)).length > 0
              ? [
                  ...acc,
                  ...itm.type.filter(t => !acc.includes(t))
                ]
              : acc
            : acc.includes(itm.type)
              ? acc
              : [...acc, itm.type]
          ), []
        )
    }
}

Explanation解释

  1. reduce is used on the array this.examplesList reduce用于数组this.examplesList
  2. Each item itm is processed and acc is the accumulator/aggregator (initially set to an empty array [] )每个项目itm被处理并且acc是累加器/聚合器(最初设置为空数组[]
  3. if itm.type is an Array, then如果itm.type是一个数组,那么
  • if any elements in itm.type array is not already present in acc array, include it (by using the ... spread operator)如果itm.type数组中的任何元素不存在于acc数组中,则包括它(通过使用...扩展运算符)
  1. otherwise (ie, itm.type is a string)否则(即, itm.type是一个字符串)
  • if it is not already in acc , then include it (again, using ... spread operator)如果它不在acc中,则包含它(再次,使用...扩展运算符)

That's it !而已 !

Please comment if any further clarification/s or question/s.如果有任何进一步的澄清或问题,请发表评论。

Code snippet代码片段

 const examples = [{ name: "Example 1", type: ["Meat", "Water", "Dairy"], showDetail: false }, { name: "Example 2", type: "Fruit", showDetail: false }, { name: "Example 3", type: "Vegetable", showDetail: false } ]; const getUniqueTypes = (arr = examples) => ( arr.reduce( (acc, itm) => ( Array.isArray(itm.type)? itm.type.filter(t =>.acc.includes(t))?length > 0. [..,acc. ...itm.type.filter(t =>:acc:includes(t)) ]. acc. acc?includes(itm:type). acc. [.,.acc, itm;type] ). [] ) ); console.log(getUniqueTypes());

Here's an abstract way of doing that using a Set .这是使用Set的一种抽象方法。 Sets guarantee unique values meaning there's no need to check if an item is present or not.设置保证唯一值意味着无需检查项目是否存在。

Using just an array will become increasingly expensive to check if an item was already added as it will have to scan the entire array for each includes , O(n) time complexity.仅使用数组来检查是否已添加项目将变得越来越昂贵,因为它必须扫描整个数组以查找每个includesO(n)时间复杂度。

 const examples = [{ name: "Example 1", type: ["Meat", "Water", "Dairy"], showDetail: false }, { name: "Example 2", type: "Fruit", showDetail: false }, { name: "Example 3", type: "Vegetable", showDetail: false } ]; const typeSet = new Set(); let types; examples.forEach((example) => { if (Array.isArray(example.type)) { example.type.forEach(type => { typeSet.add(type); }); } else { typeSet.add(example.type); } }); types = [...typeSet]; console.log(types);

Working Demo:工作演示:

 const examples = [{ name: "Example 1", type: ["Meat", "Water", "Dairy"], showDetail: false }, { name: "Example 2", type: "Fruit", showDetail: false }, { name: "Example 3", type: "Vegetable", showDetail: false }]; let newArray = [] examples.forEach((item) => { if (typeof(item.type) === 'object') { item.type.forEach((elem) => { newArray.push(elem) }) } else { newArray.push(item.type) } }) console.log(newArray)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 推送另一个数组中每个对象内的每个对象的元素 - push elements of each object inside each object inside another array 如何按值将对象数组推送到数组内另一个 object 内的新数组变量? - How to push array of objects to a new array variable inside another object inside array by value? 如何将元素推入 Mongoose 中另一个数组中的 object 中的数组? - How to push an element into an array inside an object inside another array in Mongoose? 如何向数组中的每个 object 添加一个字段,并使用 react 和 javascript 将该结果数组推送到另一个数组? - How to add a field to each object in array and push that result array to another array using react and javascript? 如何将值推送到对象内的数组 - How to Push Value to an Array Inside an Object 如何将一个数组推入另一个数组内部的对象中? - How to push an array into an Object which is inside of another array? 如何将数组值推到另一个数组对象值javascript - how to push array value to another array object value javascript 使用push和forEach创建数组和对象 - create array and object using push and forEach 使用嵌套的 forEach 循环将对象推送到数组 - Using nested forEach loops to push and object to an array 如何将数组中存在的每个 object 的值与另一个数组的值相乘? - how to multiply value of each object present in an array with value of another array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM