6

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?

6
  • 3
    What you want is invalid syntax. Instead, explain what problem you're solving. Commented Jan 31, 2017 at 6:48
  • Yes. How about something like that: [["id",23], ["name","Jacob"], ["link",{......, ......}]] Commented Jan 31, 2017 at 6:50
  • hmm I see... its a bit complicated to explain, let me get back to you later Commented Jan 31, 2017 at 6:51
  • @MauricePerry Yes , thats what i want Commented Jan 31, 2017 at 6:52
  • answered and added demo Commented Jan 31, 2017 at 7:05

9 Answers 9

16
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

Sign up to request clarification or add additional context in comments.

5 Comments

thats close man, thanx but still it separates the keys in an array and values in a different one array[2] -> 0: id 1: 23
it is just displaying like that it is actually ["id", 23]
Arrays in JS has indexes. so if you want to reach "id" you just console.log(arr[0][0]) to see it
console.log(arr[0]); the result is ["id", 23]
@Sahil I dont need it to be separated... I am using ionic 2 and to refer to values I reference the keys only in order to get them
5
p.forEach( function (country) { 
  country.forEach( function (entry) {
    entry.push( {"value" : 'Greece', "synonyms" : 'GR'});
   });
 });

1 Comment

Hello, an explanation of the code would help other users.
2

you can try to use experimental Object.entries:

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

console.log(Object.entries(obj).map(item => ({[item[0]]:item[1]})));

for unsupported browsers you can use polyfill: https://github.com/es-shims/Object.entries

2 Comments

thats not what Im looking for...it separates the values "id",23
I added Array.map function to my code, please check again if it is your desired result
2

You could use an iterative/recursive approach with the object and their nested parts. It works for any depths.

function getKeyValue(object) {
    return Object.keys(object).reduce(function (result, key) {
        return result.concat(
            object[key] && typeof object[key] === 'object' ?
            getKeyValue(object[key]) :
            [[key, object[key]]]
        );
    }, []);
}

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

console.log(getKeyValue(data));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

2

You can use the Object.keys method to get an array of the keys, then use the Array#map method to return a new array containing individual objects for each property.

This ES6 one-liner should do it:

const splitObject = o => Object.keys(o).map(e => ({ [e]: o[e] }));

Or in ES5:

function splitObject(o) {
    return Object.keys(o).map(function(e) {
        return Object.defineProperty({}, e, { 
            value: o[e], 
            enumerable: true 
        });
    });
}

Comments

1
  var res = [];
_.transform( {
  "id": 23,
  "name": "Jacob",
  "link": {
    "rel": "self",
    "link": "www.abc.com"
  },
  "company": {
    "data": {
      "id": 1,
      "ref": 324
    }
  }
}, function(result, value, key) {
    res.push(key +':'+value);
}, {});

You can use underscore

Comments

0

Supported in all major browser, including IE11

Object.entries() gives you exactly this.

const obj = {
  id: 23,
  name: 'Jacob',
  link: {
    rel: 'self',
    link: 'www.abc.com'
  },
  company: {
    data: {
      id: 1,
      ref: 324
    }
   }
 };

Object.entries(obj);
// output:
[
    [
        "id",
        23
    ],
    [
        "name",
        "Jacob"
    ],
    [
        "link",
        {
            "rel": "self",
            "link": "www.abc.com"
        }
    ],
    [
        "company",
        {
            "data": {
                "id": 1,
                "ref": 324
            }
        }
    ]
]

Comments

0
var obj=[{"Name":ABC,"Count":123},{"Name":XYZ,"Count":456}];
var arr = [];

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

/* Here above exmple innerobj index set to 0 then we will get same data into arr if u not menstion then arr will conatins arr[0] our result. then we need to call first record obj arr[0][0] like this*/

Comments

0
const foo = { "bar": "foobar", "foo": "foobar" }
Object.entries(foo)

should result in:

[["bar", "foobar"], ["foo", "foobar"]]

maybe there's a function to pass to convert all commas to colons

Here's the documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.