Actualmente estoy tratando de codificar una aplicación con javascript. Extrae datos de una base de datos y la respuesta que obtengo es algo así:
{ "values":[ { "name": "Munich", "location": "Germany", "native_lang": "German", }, { "name": "London", "location": "England", "native_lang": "English", }, { "name": "Rome", "location": "Italy", "native_lang": "Italian", } ] }Pero necesito tener el JSON así:
[ { "name": "Munich", "location": "Germany", "native_lang": "German", }, { "name": "London", "location": "England", "native_lang": "English", }, { "name": "Rome", "location": "Italy", "native_lang": "Italian", } ] ¿Cómo puedo eliminar el objeto de values principales en mi JSON?
RESPUESTA CORTA:
Simplemente acceda a la propiedad de values como un objeto de JavaScript.
RESPUESTA LARGA:
No publicaste el fragmento de código JavaScript, por lo que es bastante difícil darte una respuesta adecuada.
Suponiendo que tiene el siguiente código:
const jsonString = getDataFromTheDB() const jsonObject = JSON.parse(jsonObject) // still has the "values" layer const values = jsonObject.values // what you want, without the "values" layer // BONUS: Just in case you want to convert the object back to a JSON string but without the "values" layer const valuesJSON = JSON.stringify(values, undefined, 2)Basado en esta publicación :
solo haz esto (considera json la variable que contiene tu json):
var key = "values"; var results = json[key]; delete json[key]; json = results; console.log(json) generará lo siguiente:
[ { "name": "Munich", "location": "Germany", "native_lang": "German", }, { "name": "London", "location": "England", "native_lang": "English", }, { "name": "Rome", "location": "Italy", "native_lang": "Italian", } ] Pero ni siquiera tiene que hacer los últimos 2 pasos del fragmento de código anterior, también puede usar directamente la variable de results y obtener la misma salida de console.log(results) .
Podría tomar el objeto y crear una nueva variable solo con la matriz.
var vals = { "values":[ { "name": "Munich", "location": "Germany", "native_lang": "German", }, { "name": "London", "location": "England", "native_lang": "English", }, { "name": "Rome", "location": "Italy", "native_lang": "Italian", } ] } var arr = vals.values; console.log(arr);