简体   繁体   中英

Rename unknow key from json array in javascript

I been searching with no success, i would like to iterate over a json object but this have diferent names on keys, below my code

  [{
    "05115156165165" :{
        "name":"John",
        "Phone":"515555"
    },
    "111111111":{
        "name":"John",
        "Phone":"515555"
    }
  }]

So basically i need in the following way:

    [{
    "data" :{
        "name":"John",
        "Phone":"515555"
    },
    "data":{
        "name":"John",
        "Phone":"515555"
    }
  }]

You can use Object.values to retrieve values for unknwon keys and reduce to transform input array:

 let input = [{ "05115156165165":{ "name":"John", "Phone":"515555" }, "111111111":{ "name":"John", "Phone":"5155557" } }]; let result = input.reduce((acc,cur)=> { Object.values(cur).forEach( obj => {acc.push({ data: obj });} ) return acc; },[]); console.log(result);

The key is use Object.entries to iterate through all the keys in the object, which in this case it has only 1 that the name is unknown in every object.

 const data = [{ "05115156165165": { "name": "John1", "Phone": "1111111" }, "111111111": { "name": "John2", "Phone": "2222222" } }] let result = [] data.forEach(d => { for (const [key, value] of Object.entries(d)) { result.push({ data: { name: value.name, Phone: value.Phone } }) } }) console.log(result)

You can do something like this:

let data = [{
  "05115156165165": {
    "name": "John1",
    "Phone": "1111111"
  },
  "111111111": {
    "name": "John2",
    "Phone": "2222222"
  }
}]
let result = []
data.forEach(d => {
  Object.keys(d).forEach(el => {
    result.push({
      data: d[el]
    })
  })
})
console.log(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM