Go through all keys of a json

Asked

Viewed 7,656 times

3

I want to go through all the keys of a json so I can get all of its values. Ex:

{
  "logistics_provider": "{{lp_name}}",
  "shipper": "{{co_common_name}}",
  "invoice_key": "{{ae_identifier}}",
  "invoice_series": "{{ae_identifier}}",
  "volume_number": "1",
   "events": [
  {
        "event_date": "{{ae_date}}",
        "original_code": "{{ae_code_event}}",
        "original_message": "{{ae_comment}}"
  }]
}

So I want the values {{lp_name}}, {{co_common_name}} etc. ...

  • You want even inside those who are arrays?

2 answers

4


You can scroll through the object with the for...in and check what type of property:

var objeto =  {
  "logistics_provider": "{{lp_name}}",
  "shipper": "{{co_common_name}}",
  "invoice_key": "{{ae_identifier}}",
  "invoice_series": "{{ae_identifier}}",
  "volume_number": "1",
    "events": [
  {
        "event_date": "{{ae_date}}",
        "original_code": "{{ae_code_event}}",
        "original_message": "{{ae_comment}}"
  }]
};

var resultado = [];

function percorrer(obj) {
  for (var propriedade in obj) {
    if (obj.hasOwnProperty(propriedade)) {
      if (typeof obj[propriedade] == "object") {
        percorrer(obj[propriedade]);
      } else {
        resultado.push(obj[propriedade]);
      }
    }
  }
}

percorrer(objeto);
console.log(JSON.stringify(resultado));

In the ES6 you can use the reduce and the Sintaxe de espalhamento:

const extrair = (origem) => {
  // Se for um array realiza a extração de seus itens
  if (Array.isArray(origem)) {
    return origem.reduce((acumulador, item) => [...acumulador, ...extrair(item)], []);
  }

  // Se for um objeto, verifica se algum dos valores é um array para realizar a extração
  return Object.values(origem).reduce((acumulador, item) => (
    [...acumulador, ...(Array.isArray(item) ? extrair(item) : [item])]
  ), []);
};

// Teste da função
const objeto =  {
  "logistics_provider": "{{lp_name}}",
  "shipper": "{{co_common_name}}",
  "invoice_key": "{{ae_identifier}}",
  "invoice_series": "{{ae_identifier}}",
  "volume_number": "1",
    "events": [
  {
        "event_date": "{{ae_date}}",
        "original_code": "{{ae_code_event}}",
        "original_message": "{{ae_comment}}"
  }]
};

console.log(extrair(objeto));


reduce

The method reduce() performs a function reducer (provided by you) for each member of the array, resulting in a single return value.

Example:

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15


Scattering Syntax (Spread syntax).

Scattering Syntax (Spread syntax) allows an iterable object such as an array expression or a string to be expanded where zero or more arguments (for function calls) or elements (for literal arrays) are expected, or an object to be expanded where zero or more pairs property:value (for literal objects) are expected.

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
// expected output: 6

console.log(sum.apply(null, numbers));
// expected output: 6

Reference: Recursively looping through an Object to build a Property list.

3

Taking into account that the JSON structure is this, you can use for. in to read the keys and values of the two levels:

var obj = {
  "logistics_provider": "{{lp_name}}",
  "shipper": "{{co_common_name}}",
  "invoice_key": "{{ae_identifier}}",
  "invoice_series": "{{ae_identifier}}",
  "volume_number": "1",
  "events": [{
    "event_date": "{{ae_date}}",
    "original_code": "{{ae_code_event}}",
    "original_message": "{{ae_comment}}"
  }]
};

for (key in obj) { // obtém as chaves do objeto
  // se o valor for diferente de objeto (caso events)
  if (typeof obj[key] !== 'object') 
    console.log("Chave: " + key + " - Valor: " + obj[key]);
  else
    // se o valor for um array de objetos, é iterado o array
    // e as chaves de cada objeto
    obj[key].forEach(function(item) {
      for (key2 in item) {
        console.log("Chave: " + key2 + " - Valor: " + item[key2]);
      }
    });
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.