亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

根據給定路徑填充JavaScript中對象的所有節點

根據給定路徑填充JavaScript中對象的所有節點

ABOUTYOU 2023-08-10 10:53:00
假設我有一個像這樣的對象:{  id: 1,  name: 'E1',  children: [    {      id: 2,      name: 'E2',      children: [        {          id: 3,          name: 'E3',        },        {          id: 7,          name: 'E7',        },      ],    },    {      id: 4,      name: 'E4',      children: [        {          id: 5,          name: 'E5',          children: [            {              id: 6,              name: 'E6',            },          ],        },      ],    },  ],};我想獲取給定路徑的填充了對象數據的樹,例如children.0.children.0應該返回{  id: 1,  name: 'E1',  children: [    {      id: 2,      name: 'E2',      children: [        {          id: 3,          name: 'E3',        },      ],    } ]}我有這樣的東西,但它實際上不起作用:const createPath = (obj, path, value = null) => {  let current = obj;  while (path.length > 1) {    const [head, ...tail] = path;    path = tail;    if (current[head] === undefined) {      current[head] = {};    }    current = current[head];  }  current[path[0]] = value;  return obj;};有任何想法嗎?
查看完整描述

1 回答

?
HUX布斯

TA貢獻1876條經驗 獲得超6個贊

這可能是一個解決方案,但它并不能涵蓋所有場景,只是一條快樂的道路。我不知道哪些是預期的場景。


function createPath(obj, path) {

  var newObject = Object.assign({}, obj);

  var aux;

  var keys = path.split('.');

  var i = 0;

  while(i < keys.length) {

    if (aux) {

      aux[keys[i]] = [aux[keys[i]][keys[i+1]]];

      aux = aux[keys[i]][keys[i+1]];

    } else {

      aux = obj[keys[i]][keys[i+1]];

      newObject[keys[i]] = [aux];

    }

    i = i + 2;

  }

  

  return newObject;

}


查看完整回答
反對 回復 2023-08-10
  • 1 回答
  • 0 關注
  • 145 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號