簡體   English   中英

將對象推入對象數組

[英]pushing an object into an array of objects

我想將檢索到的結果作為內聯字符串結果推送到我的數組對象項中

這是我的代碼:

  arrayObject.push({ type: "type", item: itemArray });

  arrayObject.forEach((elementItem) => {
    global.forEach((element) => {
      const { items } = element;
      for (const item in items) {
        const title = items[item].title;
        elementItem.item.push({ title });
      }
    });
  });

這是我從全局,項目和標題中檢索到的json文件

  global: [
    {
      items: {
        xxx: {
          title: 'result1',
        }
      },
    }
 ]

我想要的結果是這樣的:

[ { type: 'xxx', item: [ {name: result1 } ] } ]

在這里,我使用了reduce和object.values來產生預期的結果。

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_objects/Object/values

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

 const global = [{ way: 'type1', items: { get: { title: 'result1', }, post: { title: 'result2', }, put: { title: 'result3', }, }, }, { way: 'type2', items: { get: { title: 'test1', }, post: { title: 'test2', }, put: { title: 'test3', }, }, }, ] function mapJsonToTypes(arr) { const typeAndTitles = (acc, {items, way: type}) => { return [...acc, {type, item: getTitlesFromItems(items)}] } return arr.reduce(typeAndTitles, []); } function getTitlesFromItems(items = {}) { return Object.values(items).map(({ title }) => title) } console.log(mapJsonToTypes(global)); 

暫無
暫無

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

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