Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

202
Vistas
Convert array in JSON file to string

Here's a snippet of my JSON object (EDITED) -

[{
    "traditional": "%",
    "simplified": "%",
    "referencedTraditional": [],
    "referencedSimplified": [],
    "pinyinNumeric": "pa1",
    "pinyinDiacritic": "pā",
    "definitions": [
        "percent (Tw)"
    ],
    "definitionsDiacritic": [
        "percent (Tw)"
    ]
},
{
"traditional":"龠","simplified":"龠","referencedTraditional":[{"cp":"9fa0","c":"龠"}],"referencedSimplified":[{"cp":"9fa0","c":"龠"}],"pinyinNumeric":"yue4","pinyinDiacritic":"yuè","definitions":["ancient unit of volume (half a 合[ge3], equivalent to 50ml)","ancient flute"],"definitionsDiacritic":["ancient unit of volume (half a 合[gě], equivalent to 50ml)","ancient flute"]},
    {"traditional":"龡","simplified":"龡","referencedTraditional":[{"cp":"9fa1","c":"龡"}],"referencedSimplified":[{"cp":"9fa1","c":"龡"}],"pinyinNumeric":"chui4","pinyinDiacritic":"chuì","definitions":["to blow (a flute)","archaic version of 吹"],"definitionsDiacritic":["to blow (a flute)","archaic version of 吹"]},
]

I want to convert every key called definitions from an array into a string.

E.g. From ["percent (Tw)"] to "percent (Tw)". Basically, I don't want the array brackets.

So far, I've tried looping through the file and converting every "definitions" key with JSON.stringify() or toString() -

translations.forEach(key => JSON.stringify((key.definitions)))

However, nothing changes in the outputted file.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Issue with the code is the one below

translations.forEach(key => JSON.stringify((key.definitions)))

Simply running this statement will not update the value for the key inside that object. You have to update the object for this.

Logic.

  • Loop through the keys in the object translations. I used Object.entries(translations).forEach for that.
  • Check each key, whether it includes "definitions" in that key.
  • If the key has "definitions" in that, run your stringification logic. I prefer Array.join() compared to JSON.stringify.
  • Update the key of that object.

Working Fiddle

const translations = {
    "traditional": "%",
    "simplified": "%",
    "referencedTraditional": [],
    "referencedSimplified": [],
    "pinyinNumeric": "pa1",
    "pinyinDiacritic": "pā",
    "definitions": [
        "percent (Tw)"
    ],
    "definitionsDiacritic": [
        "percent (Tw)"
    ]
}
Object.entries(translations).forEach(([key, value]) => key.includes('definitions') ? translations[key] = translations[key].join("") : null);
console.log(translations);

about 4 years ago · Juan Pablo Isaza Denunciar

0

const obj = {
    traditional: '%',
    simplified: '%',
    referencedTraditional: [],
    referencedSimplified: [],
    pinyinNumeric: 'pa1',
    pinyinDiacritic: 'pā',
    definitions: ['percent (Tw)'],
    definitionsDiacritic: ['percent (Tw)'],
};

const returnStringDefinitions = (obj) => {
    const arr = [];
    for (const [key, value] of Object.entries(obj)) {
        if (key === 'definitions') arr.push(value.toString());
    }
    return arr;
};

console.log(returnStringDefinitions(obj));

about 4 years ago · Juan Pablo Isaza Denunciar

0

I think what may be happening for you is that you aren't saving the resulting array anywhere. The approach could be to create a new object.

const obj = {
    traditional: '%',
    simplified: '%',
    referencedTraditional: [],
    referencedSimplified: [],
    pinyinNumeric: 'pa1',
    pinyinDiacritic: 'pā',
    definitions: ['percent (Tw)'],
    definitionsDiacritic: ['percent (Tw)'],
};

const output = Object.keys(obj).reduce((accumulator, currentKey) => {
    const currentValue = obj[currentKey];
    if (currentKey === 'definitions' && Array.isArray(currentValue)) {
            accumulator[currentKey] = currentValue.join(''); 
    } else {
        accumulator[currentKey] = currentValue;
    }
    return accumulator;
}, {})

console.log(output);

This solution checks if it is an array, and also just joins everything in the array just in case there are multiple things in the array, but how this is handled is really up to you :)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda