Как вытащить вложенный объект на основе совпадения строк? - PullRequest
1 голос
/ 26 сентября 2019

activePath будет динамически изменяться в зависимости от вызова API, как получить объект на основе строки activePath, которая соответствует вложенному объекту?

примеры путей: Drug/GetRefills в этом случае следует нажать data.Drug.getRefills, а еслипуть Payment/getAccount должен толкать data.Payment.getAccount

main.js

const data = 
    [{
        id: 11,
        name: "Drug",
        children: [{
            id: 12,
            name: "getRefills"
        }, {
            id: 13,
            name: "getDetails"
        }]
    }, {
        id: 14,
        name: "Payment",
        children: [{
            id: 15,
            name: "getAccount"
        }, {
            id: 16,
            name: "getAccountDetails"
        }]
    }]


  function getModelData(data){
        var activePath = "Drug/GetRefills";
        var _interfaces = [];   
        $.each(data, function(id, item){
            if (activePath.toLowerCase().includes(item.name)) {
                console.log('OBJ', item);
                _interfaces.push(item);   // it should push getrefills object into interfaces   
            } 
        });

         return _interfaces;
    }

Ответы [ 4 ]

3 голосов
/ 26 сентября 2019

Вы можете использовать рекурсию для поиска объекта (аналогично DFS):

const data = [{
  id: 11,
  name: "Drug",
  children: [{
    id: 12,
    name: "getRefills"
  }, {
    id: 13,
    name: "getDetails"
  }]
}, {
  id: 14,
  name: "Payment",
  children: [{
    id: 15,
    name: "getAccount"
  }, {
    id: 16,
    name: "getAccountDetails"
  }]
}];


function getModelData(path) {
  function find(arr, [key, ...rest]) {
    const obj = arr.find(o => o.name === key);
    if (!obj) return null;
    return rest.length ? find(obj.children || [], rest) : obj;
  }

  return find(data, path.split('/'));
  // Instead of returning, add the found object to _interfaces
}

console.log(getModelData('Drug/getRefills'));
console.log(getModelData('Drug/getRefillsss'));
console.log(getModelData('Payment/getAccountDetails'));
1 голос
/ 26 сентября 2019

Я думаю, что вы ищете какую-то утилиту, например квартиру.Вот самый простой пример.

const data = [
  {
    id: 11,
    name: "Drug",
    children: [
      {
        id: 12,
        name: "getRefills"
      },
      {
        id: 13,
        name: "getDetails"
      }
    ]
  },
  {
    id: 14,
    name: "Payment",
    children: [
      {
        id: 15,
        name: "getAccount"
      },
      {
        id: 16,
        name: "getAccountDetails"
      }
    ]
  }
];
function flat(array) {
    return array.reduce((m, {name, children}) => {
        children.forEach((child) => {
            const {name:cname} = child
            const fullName = `${name.toLowerCase()}/${cname.toLowerCase()}`
            if(!m[fullName]) m[fullName] =[]
            m[fullName].push(child)
        })
        return m
    },{})
}

function getModelData(path, data) {
  return flat(data)[path.toLowerCase()];
}
var activePath = "Drug/GetRefills";
console.log(getModelData(activePath, data));

//Output
[ { id: 12, name: 'getRefills' } ]
0 голосов
/ 26 сентября 2019
const data = [{
  id: 11,
  name: "Drug",
  children: [{
    id: 12,
    name: "getRefills"
  }, {
    id: 13,
    name: "getDetails"
  }]
}, {
  id: 14,
  name: "Payment",
  children: [{
    id: 15,
    name: "getAccount"
  }, {
    id: 16,
    name: "getAccountDetails"
  }]
}];

function getModelData(data,activePath){
        var activePaths = activePath.split("/"),
            _interfaces = [];   
        $.each(data, function(index, item){
            if(!item.children || item.children.length == 0){
                return false; //break
            }
            if(activePaths[0].toLowerCase() != item.name.toLowerCase()){
                return true;//continue
            }
            childs = item.children;
            $.each(childs,function(name,item){
                item.name.toLowerCase() === activePaths[1].toLowerCase() && _interfaces.push(item);
            });
        });

         return _interfaces;
    }

console.log(getModelData(data,'Drug/getRefills'));
console.log(getModelData(data,'Payment/getAccountDetails'));

0 голосов
/ 26 сентября 2019

Вот пример того, как вы можете получить правильный объект из данных с помощью функции фильтра из lodash .

const activePath = "Drug/getRefills";

// get name
let name = activePath.substr(0, activePath.indexOf('/'));

// get detail
let detail = activePath.substr(activePath.indexOf('/') + 1);


const data = 
    [{
        id: 11,
        name: "Drug",
        children: [{
            id: 12,
            name: "getRefills"
        }, {
            id: 13,
            name: "getDetails"
        }]
    }, {
        id: 14,
        name: "Payment",
        children: [{
            id: 15,
            name: "getAccount"
        }, {
            id: 16,
            name: "getAccountDetails"
        }]
}]

// Get data with lodash filter
const currentName  = _.filter(data, d => d.name === name);
const currentDetail = _.filter(currentName[0].children, c => c.name === detail);
console.log(currentDetail[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...