簡體   English   中英

使用 Javascript/Vue.Js 在數組中合並數組

[英]Merge arrays within an array using Javascript/Vue.Js

我有一個包含 3 個數組的固定 JSON 數組。 獲取 JSON 后,我試圖將它們合並到一個數組中。 這是我嘗試過的,但 Vue.JS 數組似乎是空的。

以前的

this.items = items;

新嘗試

this.items = items.concat.apply([], arrays);

我在下面的鏈接中放了一個 3 頁演示的例子:

https://arraydemo.netlify.com

<body>
<!-- Page List -->
<div class="container text-center mt-5" id="app">
    <h1 class="display-4">Vue Page Output:</h1>
    <!--<h2>{{items[0][0].page1}}</h2>-->
    <h2>{{items.page1}}</h2>
</div>
<div class="container text-center mt-5">
    <h3>Other Pages</h3>
    <a href="products.html">Products</a>
    <a href="contactus.html">Contact Us</a>
</div>
<!-- /.container -->

<script type="text/javascript">
    const app = new Vue({
    el: '#app',
    data: {
        items: []
    },
    created: function () {
        fetch('test.json')
        .then(resp => resp.json())
        .then(items => {
            this.items = items.concat.apply([], arrays);
        })
    }
    });
</script>
</body>

JSON

[
    [
    {
        "page1": "Company Name"
    }
    ],
    [
    {
        "products": "Product List"
    }
    ],
    [
    {
        "contactus": "Contact Us at Acme Corp"
    }
    ]
]

所需的 JSON 輸出

JSON

[
    {
        "page1": "Company Name"
    },
    {
        "products": "Product List"
    },
    {
        "contactus": "Contact Us at Acme Corp"
    }
]

您可以遍歷每個對象,其中每個對象都是一個數組,循環遍歷嵌套數組並將對象推送到一個新數組。

我希望這能解決你的問題

 var arr = [ [ { "page1": "Company Name" } ], [ { "products": "Product List" } ], [ { "contactus": "Contact Us at Acme Corp" } ] ] // normal way var mergedArrNormalWay = []; arr.forEach(o => { o.forEach(so => mergedArrNormalWay.push(so)) }) // using concat var merged = [].concat.apply([], arr); console.log("merged in a normal iteration way using for each", mergedArrNormalWay); console.log("reduced way", merged)

鑒於上面的 JSON 示例和所需的輸出,在外部數組上調用.flat()應該適合您。

someArray.flat()

MSDN - Array.prototype.flat()

您的問題不清楚您最終是想要一個對象數組還是一個數組數組。 我假設您需要一個數組數組(因為這稍微復雜一些),但是如果您需要一個對象數組,您可以簡化以下內容(特別是Object.entries ):

merged = [];

items.map(
  item => item.forEach(inner => (
    merged.push(Object.entries(inner).flat())
  ))
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM