I have an array

[ { "name":"BMW", "price":"55 000", "color":"red", }, { "name":"MERSEDEC", "price":"63 000", "color":"blue", } ]; 

It is necessary to write a function that will accept an input at the input and instead of the name will output a class instead of the name

 "class":"MERSEDEC", "price":"63 000", "color":"blue", 

What method to use?

  • where is marka ? - Dmytryk
  • Sorry, fixed - Love GIAS

3 answers 3

If for some reason you want to leave the original array in its original form:

 let data = [{ "name": "BMW", "price": "55 000", "color": "red", }, { "name": "MERSEDEC", "price": "63 000", "color": "blue", } ]; function transform(arr) { return arr.map(item => { let newItem = Object.assign({}, item); newItem.class = item.name; delete newItem.name; return newItem; }) } console.log(transform(data)); 

     var data = [{ "name": "BMW", "price": "55 000", "color": "red", }, { "name": "MERSEDEC", "price": "63 000", "color": "blue", } ]; function nameToClass(arr) { arr.forEach(i => { i.class = i.name; delete i.name; }); return arr; } console.log(nameToClass(data)); 

    How to make so that the class was the first, and not at the end?

     var data = [{ "name": "BMW", "price": "55 000", "color": "red", }, { "name": "MERSEDEC", "price": "63 000", "color": "blue", } ]; function nameToClass(arr) { var str = JSON.stringify(arr); str = str.replace(/name/g, "class"); arr.splice(0, arr.length, ...JSON.parse(str)); return arr; } console.log(nameToClass(data)); 

    • Object {price: "55,000", color: "red", class: "BMW"} that's what it does. How to make so that the class was the first, and not at the end? - Love GIAS 2:43 pm
    • @LoveGIAS Why? - Yaant pm

    If you need to replace the name with the class , then you can simply do everything in a loop:

     var items; // Ваш массив с данными. var i; for(i = 0; i < items.length; i++){ items[i].class = items[i].name; delete items[i].name; } 
    • You need to use the method - Love GIAS