How to change the value structure specified in an array object by one method is not fixed

let data = [
    {
        id: 1,
        price1: 5,
        price2: 4
    }

let data1 = [
  {
    id: 1,
    price: {
      price1: 6
    }
  }
]

let data2 = [
  {
    id: 1,
    price: {
      price1: {
        price2: 7
      }
    }
  }
]

//  vlaue key

test(data, "price1,price2")
test(data1, "price.price1")
test(data2, "price.price1.pricew")

function test (data, price) {

}
Jul.22,2021

let data = [
  {
    id: 1,
    price1: 5,
    price2: 4
  },
  {
    id: 2,
    price1: 5,
    price2: 4
  }
]

let data1 = [
  {
    id: 1,
    price: {
      price1: 6
    }
  },
  {
    id: 2,
    price: {
      price1: 6
    }
  }
]

let data2 = [
  {
    id: 1,
    price: {
      price1: {
        price2: 7
      }
    }
  },
  {
    id: 2,
    price: {
      price1: {
        price2: 7
      }
    }
  }
]

function test (data, price) {
  let keys = price.split(',').filter(key => key)
  keys.forEach(key => {
    let list = key.split('.').filter(key => key)
    let last = list.pop()
    data.forEach(item => {
      let tmpList = list.map(cur => cur)
      let cur
      let d = item
      while(cur = tmpList.shift()) {
        d = d[cur]
      }
      d[last] = '' + d[last]
    })
  })
}

test(data, 'price1,price2')
test(data1, 'price.price1')
test(data2, 'price.price1.price2')

console.log(data, data1, data2)

Why is the structure unstable? In general, this situation is that the design of the data structure is not reasonable.

of course, it may also be because the data sources are scattered, in which case it is better to write an adapter to transform the data structure for each source-- of course, if several array structures change very regularly, you can also use an adapter to solve the problem.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e497ba-44d48.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e497ba-44d48.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?