0

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"
    }
  }]

6
  • looks like you wrapped all the objects within an object, afaik - cannot have same key ("data"). Commented Jul 9, 2020 at 5:49
  • 2
    Just noticed, you need to have different key for each sub object otherwise last one will overwrite older one. Commented Jul 9, 2020 at 5:51
  • 1
    @fedesc, {a:1,a:2,a:3}=={a:3} = the 2 and 3 "disappear". If you look closely, you'll see that the expected is one object... Commented Jul 9, 2020 at 5:53
  • 1
    That's neither a "json array" nor a "json object" (There's no such thing as a "JSON Object"). That's an array with one object Commented Jul 9, 2020 at 5:53
  • @iAmOren I did checked again that's why i removed my comment haha didn't notice the extra {} Commented Jul 9, 2020 at 5:55

3 Answers 3

1

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.