Как найти все указанные c ключи на нескольких уровнях NESTED JSON в одном l oop, и для каждого из них изменить значение - PullRequest
0 голосов
/ 31 марта 2020

как получить номер индекса для каждого объекта в массиве. У меня JSON с несколькими вложенными массивами объектов, и мне нужно установить номер индекса ключа POSITION.

Я получаю это JSON динамически, и мне нужно l oop через JSON, и на каждом POSITION ключе необходимо установить indexOF() число, чтобы получить позицию объекта внутри массив.

Моя проблема в том, как найти все ключи с именем POSITION и установить indexOf() число для значения?

Я знаю, и я пытаюсь получить его в l oop для каждого вложенного массива, но есть ли ЛУЧШИЙ способ? Более быстрый путь?

Вот пример с вложенным for loops

Thnx

Вот JSON

{
    "id": 175,
    "name": "dag",
    "title": "dfgd",
    "page": [{
        "id": 551,
        "name": "page1",
        "title": "Page 1",
        "position": 0,       ---> here I need set index number for obj in this page array
        "questions": [{
            "id": 70,
            "name": "text1",
            "text": "Questitexton 1",
            "position": 0,         ---> here I need set index number for obj in this questions array
            "data": [{
                "id": 56,
                "name": "data",
                "position": 0,       ---> here I need set index number for obj in this data array
                "text": "Control 3"
            }]
        }, {
            "id": 69,
            "name": "data3",
            "text": "data 3",
            "position": 1,       ---> here I need set index number for obj in this array
            "data": [{
                "id": 55,
                "name": "data2",
                "position": 0,       ---> here I need set index number for obj in this data array
                "text": "Control 3"
            }]
        }]
    }, {
        "id": 552,
        "name": "page2",
        "title": "Page 2",
        "position": 1,       ---> here I need set index number for obj in this page array
        "questions": [{
            "id": 73,
            "name": "text1",
            "text": "Questitexton 1",
            "position": 0,       ---> here I need set index number for obj in this questions array
            "data": [{
                "id": 75,
                "name": "data",
                "position": 0,       ---> here I need set index number for obj in this data array
                "text": "Control 3"
            }]
        }, {
            "id": 45,
            "name": "data3",
            "text": "data 3",
            "position": 1,       ---> here I need set index number for obj in this questions array
            "data": [{
                "id": 798,
                "name": "data2",
                "position": 0,       ---> here I need set index number for obj in this data array
                "text": "Control 3"
            }]
        }]
    }]
}

Моя текущая попытка

const animals = [{
  id: 175,
  name: "dag",
  title: "dfgd",
  page: [{
      id: 551,
      name: "page1",
      title: "Page 1",
      position: null,
      questions: [{
          id: 70,
          name: "text1",
          text: "Questitexton 1",
          position: null,
          data: [{
            id: 56,
            name: "data",
            position: null,
            text: "Control 3"
          }]
        },
        {
          id: 69,
          name: "data3",
          text: "data 3",
          position: null,
          data: [{
            id: 55,
            name: "data2",
            position: null,
            text: "Control 3"
          }]
        }
      ]
    },
    {
      id: 552,
      name: "page2",
      title: "Page 2",
      position: null,
      questions: [{
          id: 73,
          name: "text2",
          text: "Questitexton 1",
          position: null,
          data: [{
            id: 75,
            name: "data",
            position: null,
            text: "Control 3"
          }]
        },
        {
          id: 45,
          name: "data5",
          text: "data 3",
          position: null,
          data: [{
            id: 798,
            name: "data2",
            position: null,
            text: "Control 3"
          }]
        }
      ]
    }
  ]
}];

for (let data of animals) {
  for (let data1 of data.page) {
    data1.position = data.page.indexOf(data1);
    for (let data2 of data1.questions) {
      data2.position = data1.questions.indexOf(data2);
      for (let data3 of data2.data) {
        data3.position = data2.data.indexOf(data3);
      }
    }
  }
}

console.log(animals);

Ответы [ 2 ]

1 голос
/ 31 марта 2020

Вы можете клонировать объект и добавить индекс, если найден position.

const addIndex = (o, i) => Object.fromEntries(Object.entries(o).map(([k, v]) => [
    k,
    k === 'position'
        ? i
        : Array.isArray(v)
            ? v.map(addIndex)
            : v
]));

var animals = [{ id: 175, name: "dag", title: "dfgd", page: [{ id: 551, name: "page1", title: "Page 1", position: null, questions: [{ id: 70, name: "text1", text: "Questitexton 1", position: null, data: [{ id: 56, name: "data", position: null, text: "Control 3" }] }, { id: 69, name: "data3", text: "data 3", position: null, data: [{ id: 55, name: "data2", position: null, text: "Control 3" }] }] }, { id: 552, name: "page2", title: "Page 2", position: null, questions: [{ id: 73, name: "text2", text: "Questitexton 1", position: null, data: [{ id: 75, name: "data", position: null, text: "Control 3" }] }, { id: 45, name: "data5", text: "data 3", position: null, data: [{ id: 798, name: "data2", position: null, text: "Control 3" }] }] }] }],
    result = animals.map(addIndex);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
1 голос
/ 31 марта 2020

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

Мой код создает копия вашего исходного массива, но это не должно быть такой проблемой, скажем так, я уверен, что вы могли бы обойти это, если вам нравится

function getPositionedObject( objToCopy, position = 0 ) {
  // take all the keys on the object
  return Object.keys( objToCopy ).reduce( (agg, key) => {
    // get the value once
    const value = objToCopy[key];
    if (Array.isArray( value ) ) {
      // if it's an array, iterate all the items and re-use this function
      agg[key] = value.map( getPositionedObject );
    } else {
      // if it's not keep the value as is
      agg[key] = value;
    }
    return agg;
  }, { position }); // start with the position that was passed as a parameter
}

с вашим набором данных (я удалил начальные позиции из кода Вы дали, это вроде выглядит следующим образом)

const dataset = {
    "id": 175,
    "name": "dag",
    "title": "dfgd",
    "page": [{
        "id": 551,
        "name": "page1",
        "title": "Page 1",
        "questions": [{
            "id": 70,
            "name": "text1",
            "text": "Questitexton 1",
            "data": [{
                "id": 56,
                "name": "data",
                "text": "Control 3"
            }]
        }, {
            "id": 69,
            "name": "data3",
            "text": "data 3",
            "data": [{
                "id": 55,
                "name": "data2",
                "text": "Control 3"
            }]
        }]
    }, {
        "id": 552,
        "name": "page2",
        "title": "Page 2",
        "questions": [{
            "id": 73,
            "name": "text1",
            "text": "Questitexton 1",
            "data": [{
                "id": 75,
                "name": "data",
                "text": "Control 3"
            }]
        }, {
            "id": 45,
            "name": "data3",
            "text": "data 3",
            "data": [{
                "id": 798,
                "name": "data2",
                "text": "Control 3"
            }]
        }]
    }]
};

function getPositionedObject( objToCopy, position = 0 ) {
  return Object.keys( objToCopy ).reduce( (agg, key) => {
    const value = objToCopy[key];
    if (Array.isArray( value ) ) {
      agg[key] = value.map( getPositionedObject );
    } else {
      agg[key] = value;
    }
    return agg;
  }, { position });
}

console.log( getPositionedObject( dataset ) );
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...