Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

203
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda