How to manipulate these objects with Javascript?

Asked

Viewed 333 times

10

I have the following objects:

{ letter: "A", num1: "1", num2: "2", num3: "3" }
{ letter: "B", num1: "3", num2: "2", num3: "1" }
{ letter: "C", num1: "2", num2: "3", num3: "1" }

I would like to transform into a single object that takes letters as attribute and a number array/object value:

var unicoObjeto = {
  A: { num1: "1", num2: "2", num3: "3" },
  B: { num1: "3", num2: "2", num3: "1" },
  C: { num1: "2", num2: "3", num3: "1" }
};

What I got so far was:

var items = {};
var indice = [];
var data = [
    { letter: "A", num1: "1", num2: "2", num3: "3" },
    { letter: "B", num1: "3", num2: "2", num3: "1" },
    { letter: "C", num1: "2", num2: "3", num3: "1" }
];

$.each(data, function (i, val) {
    indice.push(val.letter);
});

Object.keys(data).forEach(key => {
    let newKey = indice[key];
    items[newKey] = items[key];
});

console.log(items);

Which presents the following (I don’t know how to pass the values now):

{ A: undefined, B: undefined, C: undefined }
  • 1

    In Javascript (no jQuery required): Function getUnicoObject(vector) { const unicoObject = {}; vector.foreach(Function(e) { const novoObjeto = {}; const attributes = Object.Keys(e).filter(a => a != "Letter"); attributes.foreach(a => newObject[a] = e[a]); unicoObject[e.Letter] = newObject; }); Return unicoObject; }

4 answers

11

You could use methods like the reduce, together with other Javascript features.

The logic is simple:

  • With each iteration, we want to add to the accumulator object (acc) a property whose key will be the property letter and the value will be the rest of the object.
  • Then we capture the key, then remove it from the current object (using the operator delete) and define the new property in the accumulator object.

For more information, see the documentation on reduce.

const data = [
  { letter: "A", num1: "1", num2: "2", num3: "3" },
  { letter: "B", num1: "3", num2: "2", num3: "1" },
  { letter: "C", num1: "2", num2: "3", num3: "1" }
];

const myObj = data.reduce((acc, current) => {
  // Mantemos a chave armazenada em uma variável, para que não
  // a percamos depois de deletá-la do objeto atual.
  const key = current.letter;

  // Deletamos a propriedade `letter` do objeto, já que ela será a chave:
  delete current.letter;

  // Definimos uma nova propriedade no objeto `acc` com a chave
  // lendo a letra e o valor o restante do objeto.
  acc[key] = current;

  // Passamos para a próxima iteração:
  return acc;
}, {});

console.log(myObj);

If you want, you can even use the most modern features of Javascript, such as the function Object.assign:

const data = [
  { letter: 'A', num1: '1', num2: '2', num3: '3' },
  { letter: 'B', num1: '3', num2: '2', num3: '1' },
  { letter: 'C', num1: '2', num2: '3', num3: '1' }
];

const myObj = data.reduce(
  (acc, { letter, ...current }) => Object.assign(acc, {
    [letter]: current
  }),
  {}
);

console.log(myObj);

Could also use the scattering notation of objects (...), although it can be less efficient when recreating the object several times. Learn more here.

And if you want to use the $.each from jQuery, can do so:

const data = [
  { letter: 'A', num1: '1', num2: '2', num3: '3' },
  { letter: 'B', num1: '3', num2: '2', num3: '1' },
  { letter: 'C', num1: '2', num2: '3', num3: '1' }
];

const myObj = {};

$.each(data, (index, current) => {
  const key = current.letter;
  delete current.letter;
  myObj[key] = current;
});

console.log(myObj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  • 2

    Excellent response!

8


For each element of data apply a function that adds the property items[val.letter] the value val and then remove the letter with the operator delete in delete val.letter

var items = {};
var data = [
    { letter: "A", num1: "1", num2: "2", num3: "3" },
    { letter: "B", num1: "3", num2: "2", num3: "1" },
    { letter: "C", num1: "2", num2: "3", num3: "1" }
];

$.each(data, (i, val) => {    
    items[val.letter] = val; 
    delete val.letter;
});


console.log(items);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

4

Creates a constructor function to populate the items of your object.

var items = {};
var indice = [];
var data = [
    { letter: "A", num1: "1", num2: "2", num3: "3" },
    { letter: "B", num1: "3", num2: "2", num3: "1" },
    { letter: "C", num1: "2", num2: "3", num3: "1" }
];

$.each(data, function (i, val) {
    indice.push(val.letter);
});

// Função Construtora
function ItemsLetter(num1, num2, num3) {
    this.num1 = num1;
    this.num2 = num2;
    this.num3 = num3;
}

data.forEach(function(element, key) {
    let newKey = element.letter;
    items[newKey] = new ItemsLetter(element.num1, element.num2, element.num3
    )
});

console.log(items);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

2

From what I understand you want to make a matrix, of the letters is this?

var data = [
    { letter: "A", num1: "1", num2: "2", num3: "3" },
    { letter: "B", num1: "3", num2: "2", num3: "1" },
    { letter: "C", num1: "2", num2: "3", num3: "1" }
];

var collection = [];
for(var i in data) {
   collection[data[i].letter] = [data[i].num1, data[i].num2,  data[i].num3];
}

console.log(collection);

Or on object:

 var collection = [];
    for(var i in data) {
       collection[data[i].letter] = {num1:data[i].num1, num2:data[i].num2,  num3: data[i].num3};
    }

Browser other questions tagged

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