将对象键及其值推送到数组

问题描述 投票:0回答:9

我有一个这样的对象:

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

我想将每个键及其值存储到 JavaScript 或打字稿中的数组中

[
    [
        "id": 23
    ], [
        "name": "Jacob"
    ], [
        "link": { ......, ......}
    ]
] 

等等

我这样做是为了可以为每个附加一个 ID。

我最好的猜测是我会循环遍历数组并为每个元素附加一个 ID/标志,我也不知道该怎么做......如何解决这个问题?

javascript typescript
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);

这里是演示 https://plnkr.co/edit/9PxisCVrhxlurHJYyeIB?p=preview


5
投票
p.forEach( function (country) { 
  country.forEach( function (entry) {
    entry.push( {"value" : 'Greece', "synonyms" : 'GR'});
   });
 });

2
投票

你可以尝试使用实验性

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]})));

对于不支持的浏览器,您可以使用polyfill:https://github.com/es-shims/Object.entries


2
投票

您可以对对象及其嵌套部分使用迭代/递归方法。它适用于任何深度。

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; }


2
投票

您可以使用

Object.keys
方法获取键数组,然后使用
Array#map
方法返回一个包含每个属性的单独对象的新数组。

这个 ES6 一行代码应该可以做到:

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

或者在 ES5 中:

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

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);
}, {});

您可以使用下划线


0
投票

支持所有主流浏览器,包括IE11

Object.entries() 正是为您提供了这一点。

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
            }
        }
    ]
]

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]);
      }
    }

/* 上面的示例中,innerobj 索引设置为 0,那么我们将在 arr 中获得相同的数据,如果您没有提及,那么 arr 将包含 arr[0] 我们的结果。 然后我们需要像这样调用第一条记录 obj arr[0][0]*/


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

应该导致:

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

也许有一个函数可以传递将所有逗号转换为冒号

这是文档
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

© www.soinside.com 2019 - 2024. All rights reserved.