Изменить рекурсивно специфические свойства из вложенного массива объектов - PullRequest
0 голосов
/ 19 октября 2018

Я застрял в проблеме, пытаясь изменить значение определенных свойств во вложенном массиве объектов:

const myObj = [
    {
        "Description":"WA State",
        "Data":[
        {
            "Description":"Years",
            "Indicators":[
            {
                "Year":2018,
                "Points":25994,
                "Goal":"28000",
            }
            ]
        },
        {
            "Description":"Local Goal",
            "Indicators":[
            {
                "Year":2018,
                "Points":25994,
                "Goal":"28000",
            }
            ]
        },
        {
            "Description":"Remote Goal",
            "Indicators":[
            {
                "Year":2018,
                "Points":55857,
                "Goal":"84000",
            }
            ]
        }
        ]
    },

    {
        "Description":"NY State",
        "Data":[
        {
            "Description":"Years",
            "Indicators":[
            {
                "Year":2018,
                "Points":21953,
                "Goal":"26000",
            }
            ]
        },
        {
            "Description":"Local Goal",
            "Indicators":[
            {
                "Year":2018,
                "Points":24195,
                "Goal":"25000",
            }
            ]
        },
        {
            "Description":"Remote Goal",
            "Indicators":[
            {
                "Year":2018,
                "Points":80857,
                "Goal":"90000",
            }
            ]
        }
        ]
    }
]

Здесь мне нужно изменить внешний вид Year свойство 2017 и все свойства Goal: 50000.

Я имею в виду массив объектов, в котором я могу объявить что-то вроде:

const newValues = [{property: 'Year', newValue: 2019}, {property: 'Goal', newValue: 50000}]

и затем использовать его для сравнения итераций по вложенному массиву объектов, используя filter или reduce?Есть идеи или предложения?

Ответы [ 2 ]

0 голосов
/ 19 октября 2018

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

const myObj = [
  {
    Description: "WA State",
    Data: [
      {
        Description: "Years",
        Indicators: [
          {
            Year: 2018,
            Points: 25994,
            Goal: "28000"
          }
        ]
      },
      {
        Description: "Local Goal",
        Indicators: [
          {
            Year: 2018,
            Points: 25994,
            Goal: "28000"
          }
        ]
      },
      {
        Description: "Remote Goal",
        Indicators: [
          {
            Year: 2018,
            Points: 55857,
            Goal: "84000"
          }
        ]
      }
    ]
  },

  {
    Description: "NY State",
    Data: [
      {
        Description: "Years",
        Indicators: [
          {
            Year: 2018,
            Points: 21953,
            Goal: "26000"
          }
        ]
      },
      {
        Description: "Local Goal",
        Indicators: [
          {
            Year: 2018,
            Points: 24195,
            Goal: "25000"
          }
        ]
      },
      {
        Description: "Remote Goal",
        Indicators: [
          {
            Year: 2018,
            Points: 80857,
            Goal: "90000"
          }
        ]
      }
    ]
  }
];

function parse(arr) {
  return arr.map(obj => {
    Object.keys(obj).forEach(key => {
      if (Array.isArray(obj[key])) {
        parse(obj[key]);
      }
      
      if (key === 'Year') {
        obj[key] = 2017;
      }
      
      if (key === 'Goal') {
        obj[key] = 50000;
      }
    })
    
    return obj;
  })
}

console.log(parse(myObj));
0 голосов
/ 19 октября 2018

В качестве альтернативы используются вложенные функции forEach и функция Object.keys для циклического переключения клавиш, а функция find позволяет получить конкретный объект с новым назначаемым значением.

const myObj = [    {        "Description":"WA State",        "Data":[        {            "Description":"Years",            "Indicators":[            {                "Year":2018,                "Points":25994,                "Goal":"28000",            }            ]        },        {            "Description":"Local Goal",            "Indicators":[            {                "Year":2018,                "Points":25994,                "Goal":"28000",            }            ]        },        {            "Description":"Remote Goal",            "Indicators":[            {                "Year":2018,                "Points":55857,                "Goal":"84000",            }            ]        }        ]    },    {        "Description":"NY State",        "Data":[        {            "Description":"Years",            "Indicators":[            {                "Year":2018,                "Points":21953,                "Goal":"26000",            }            ]        },        {            "Description":"Local Goal",            "Indicators":[            {                "Year":2018,                "Points":24195,                "Goal":"25000",            }            ]        },        {            "Description":"Remote Goal",            "Indicators":[            {                "Year":2018,                "Points":80857,                "Goal":"90000",            }            ]        }        ]    }],
      newValues = [{property: 'Year', newValue: 2019}, {property: 'Goal', newValue: 50000}];
      
myObj.forEach(o => {
  o.Data.forEach(d => {
    d.Indicators.forEach(i => {
      Object.keys(i).forEach(k => {
        let nv = newValues.find(n => n.property === k);
        if (nv) i[k] = nv.newValue;
      });
    });
  });
});

console.log(myObj);
.as-console-wrapper { max-height: 100% !important; top: 0; }
...