iT邦幫忙

0

把裝置的資料全部讀取到物件裡

  • 分享至 

  • xImage

我想把裝置的資料全部讀取到物件裡, 但只讀取到最後一筆
想請問要怎麼做才能把裝置裡面的資料全部讀取到obj裡面,謝謝

let data = [
    {
        "bind": "82218018295591013",
        "account": "admin",
        "password": "0000",
        "devices": [
            {
                "ip": "192.168.0.88",
                "brand_name": "UNIVIEW",
                "name": "UNIVIEW"
            }
        ]
    },
    {
        "bind": "94907378021478863",
        "account": "admin",
        "password": "0000",
        "devices": [
            {
                "ip": "192.168.0.88",
                "brand_name": "UNIVIEW",
                "name": "UNIVIEW"
            },
            {
                "ip": "192.168.0.89",
                "brand_name": "hisharp",
                "name": "hisharp"
            }
        ]
    }
]

let obj = {};

function getObj() {
    for (let i = 0; i < data.length; i++) {
        for (let j = 0; j < data[i].devices.length; j++) {
            obj.devices = data[i].devices[j];
        }
    }

    console.log('obj :>> ', obj);
    return obj;
}

getObj();
fillano iT邦超人 1 級 ‧ 2022-01-20 16:59:50 檢舉
你用assign,理所當然只會留下最後一筆。dragonH大處理比較漂亮。如果是要照你的程式邏輯調整:
let obj = {devices: []};
然後在迴圈中:
obj.devices.push(data[i].devices[j]);
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
dragonH
iT邦超人 5 級 ‧ 2022-01-20 11:09:37
const datas = [
      {
        "bind": "82218018295591013",
        "account": "admin",
        "password": "0000",
        "devices": [
            {
                "ip": "192.168.0.88",
                "brand_name": "UNIVIEW",
                "name": "UNIVIEW"
            }
        ]
    },
    {
        "bind": "94907378021478863",
        "account": "admin",
        "password": "0000",
        "devices": [
            {
                "ip": "192.168.0.88",
                "brand_name": "UNIVIEW",
                "name": "UNIVIEW"
            },
            {
                "ip": "192.168.0.89",
                "brand_name": "hisharp",
                "name": "hisharp"
            }
        ]
    }
];

const obj = {
  devices: datas.map((data) => data.devices).flat()
};
console.log(obj);

codepen

我要發表回答

立即登入回答