Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push object keys and its values to array

I have an object like this:

{
 "id": 23,
 "name": "Jacob",
 "link": {
     "rel": "self",
     "link": "www.abc.com"
 },
 "company":{
       "data":{
           "id": 1,
           "ref": 324
       }
 }

I want to store each key with its value to an array in javascript or typescript like this [["id":23], ["name":"Jacob"], ["link":{......, ......}]] and so on

I am doing this so that I can append an ID for each. My best guess I would loop through the array and append an ID/a flag for each element, which I don't know how to do as well.... how to address this issue ? thanks

like image 291
Yasir Avatar asked Jan 31 '17 06:01

Yasir


People also ask

How do you push an object value into an array?

To push an object into an array, call the push() method, passing it the object as a parameter. For example, arr. push({name: 'Tom'}) pushes the object into the array. The push method adds one or more elements to the end of the array.

How do you push key-value pairs in array of objects?

Use the Array. forEach() method to iterate over the array. On each iteration, use dot notation to add a key/value pair to the current object. The key/value pair will get added to all objects in the array.

Does object keys work on arrays?

Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object . The ordering of the properties is the same as that given by looping over the properties of the object manually.

What does push () method in array?

The push() method adds one or more elements to the end of an array and returns the new length of the array.


2 Answers

var arr = [];

for (var prop in obj) {
   if (obj.hasOwnProperty(prop)) {
      var innerObj = {};
      innerObj[prop] = obj[prop];
      arr.push(innerObj)
   }
}
    
console.log(arr);

here is demo https://plnkr.co/edit/9PxisCVrhxlurHJYyeIB?p=preview

like image 60
Salih Şenol Çakarcı Avatar answered Oct 08 '22 07:10

Salih Şenol Çakarcı


p.forEach( function (country) { 
  country.forEach( function (entry) {
    entry.push( {"value" : 'Greece', "synonyms" : 'GR'});
   });
 });
like image 27
Manos Kaparos Avatar answered Oct 08 '22 07:10

Manos Kaparos