-4

I have an array of objects in the following form

var data = [{"name":"Lenovo Thinkpad 41A4298","website":"google"},
{"name":"Lenovo Thinkpad 41A2222","website":"google"},
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"}];

I want to convert this to

var data = [{"Brand":"Lenovo Thinkpad 41A4298","Link":"google"},
{"Brand":"Lenovo Thinkpad 41A2222","Link":"google"},
{"Brand":"Lenovo Thinkpad 41Awww33","Link":"yahoo"}];

How do I achieve this?

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205

4 Answers4

0

Using foreach loop

var data = [{
    "name": "Lenovo Thinkpad 41A4298",
    "website": "google"
  },
  {
    "name": "Lenovo Thinkpad 41A2222",
    "website": "google"
  },
  {
    "name": "Lenovo Thinkpad 41Awww33",
    "website": "yahoo"
  }
];

var Result = [];

var Key = Object.keys(data[0]); // get keys in a variable

// use index insted of specific key

data.forEach(function(item) {
  Result.push({    Brand: item[Key[0]],    Link: item[Key[1]]  });
});

console.log(Result);
Jayakrishnan
  • 1,085
  • 2
  • 11
  • 23
0

You can use map to loop thru the array. Without using the key, you can use Object.values to convert the object into an array. Assign the first element of the array on Brand and the second to Link to form a new object.

var data = [{
    "name": "Lenovo Thinkpad 41A4298",
    "website": "google"
  },
  {
    "name": "Lenovo Thinkpad 41A2222",
    "website": "google"
  },
  {
    "name": "Lenovo Thinkpad 41Awww33",
    "website": "yahoo"
  }
];

var result = data.map(o => {
  let v = Object.values(o);
  return {"Brand": v[0],"Link": v[1]};
});

console.log(result);
Eddie
  • 25,279
  • 6
  • 26
  • 53
  • Thanks for your answer. How can I filter above json data like if I want to use only yahoo related data dynamically. Example: I have select box and on clicking yahoo, only that particular name should display/return. – Karthik Gowda Jun 19 '18 at 10:08
  • Happy to help:) – Eddie Jun 19 '18 at 10:10
  • 1
    Sorry, I have to downvote - this is a very dangerous approach. The Javascript does *not* guarantee the order of fields, therefore you never know what can be in `v[0]` – libik Jun 19 '18 at 10:15
  • Yes. That is why i added to answer that the 0 element will be assigned to brand. – Eddie Jun 19 '18 at 10:17
  • OP needs to assign without the name. If you have a better approach, then you should advice OP on what to do. – Eddie Jun 19 '18 at 10:18
  • @Eddie : You probably dont understand: https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order as stated there - *It is an unordered collection of properties*. This will sometimes work, sometimes not, therefore it is not solution. – libik Jun 19 '18 at 10:20
  • I totally understand it my friend. No worries – Eddie Jun 19 '18 at 10:21
  • @Eddie - so if you understand, why you have put answer (without furhter explanation) that contains code that sometimes work and sometimes not? – libik Jun 19 '18 at 10:25
  • I put a note on my answer that the first value so on. OP cant use names on assignment to the new object. As i have said, if you have a better approach, by all means – Eddie Jun 19 '18 at 10:28
  • @Eddie - well the answer "there is no such way" is much better than answer that works only sometimes :). But I actually have the answer based on comments with OP. – libik Jun 19 '18 at 13:10
  • Well i hope you can help OP :) – Eddie Jun 19 '18 at 13:26
0

Array.map may be your friend - returns a new array with each element being the returned result of the function you pass to the .map function.

Mozilla Developer Network link to Array.map reference here

In this example

  • the function takes the first object in the array
  • Creates a new object to return
  • assigns a key of "Brand" to the new object and assigns the "name" value from the old object to it
  • assigns a key of "Link" to the new object and assigns it the "website" value from the old object to it
  • returns the new object that gets put into a new array that will eventually get assigned to newData
  • Repeats this for each element in the array

let data = [
      {"name":"Lenovo Thinkpad 41A4298","website":"google"},
      {"name":"Lenovo Thinkpad 41A2222","website":"google"},
      {"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"}
    ];
        
let newData = data.map((originalObject)=>{
  return {
    "Brand":originalObject.name,
    "Link":originalObject.website
    }
})

console.log(newData)

If you want to get even fancier - you can use object destructing here - about half way down to make the code a little neater

let data = [
          {"name":"Lenovo Thinkpad 41A4298","website":"google"},
          {"name":"Lenovo Thinkpad 41A2222","website":"google"},
          {"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"}
        ];
            
let newData = data.map(( {name,website} )=>{
  return {
    "Brand":name,
    "Link":website
    }
})

console.log(newData)
-1

Like this:

var data = [{ "name": "Lenovo Thinkpad 41A4298", "website": "google" },
{ "name": "Lenovo Thinkpad 41A2222", "website": "google" },
{ "name": "Lenovo Thinkpad 41Awww33", "website": "yahoo" }];

const newData = data.map(obj => ({ Brand: obj.name, Link: obj.website }));
console.log(newData);

To make it more dynamically, you can create some mappings:

    var data = [{ "name": "Lenovo Thinkpad 41A4298", "website": "google" },
    { "name": "Lenovo Thinkpad 41A2222", "website": "google" },
    { "name": "Lenovo Thinkpad 41Awww33", "website": "yahoo" },
    { "rate": "25", "review": "Well done" }];

    const mappings = {
      name: 'Brand',
      website: 'Link',
      review: 'Review',
      rate: 'Rate'
    }
    
    const newData = data.map(obj => {
      const newObj = {};
      const keys = Object.keys(mappings);
      keys.forEach(key => {
         if (obj[key]) {
           const newName = mappings[key];
           newObj[newName] = obj[key];
         }
      });
      return newObj;
    });

    console.log(newData);

Then you can just change "mappings" based on source data or whatever you want to do with it.

libik
  • 19,204
  • 9
  • 35
  • 72
  • Is it possible without using obj.name and obj.website – Karthik Gowda Jun 19 '18 at 09:24
  • @KarthikGowda: Any specific reason asking that? – Isaac Jun 19 '18 at 09:27
  • I will get data from API using ajax call. So name of the property will change, its not always (name, website). It may change to (rate, review) etc., – Karthik Gowda Jun 19 '18 at 09:34
  • @KarthikGowda - you have to be more specific. If it will be rate and review, do you also save it to Brand and Link? – libik Jun 19 '18 at 10:23
  • @libik - Ya I need to generate chart once I get data, coz sometimes name will be in this format(reviews.cuisine). Which I cannot read so I need to rename to specific name to generate data. in chart I should keep select box where on selecting yahoo, that particular data should display (dynamically). – Karthik Gowda Jun 19 '18 at 12:37
  • @libik Looks great but const mappings = { name: 'Brand', website: 'Link' } is not dynamic... If data has rate and review, then we need to change this section right? – Karthik Gowda Jun 19 '18 at 13:39
  • @KarthikGowda - I dont know what exactly you want to do with that... If you have object, you have to know what keys it has, because the order is not guaranteed. Or you have to choose different metric (is it number, is it shorter/longer) etc. I have updated it so you put more than 2 transformations... – libik Jun 19 '18 at 13:48