Javascript 将对象键及其值推送到数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41951269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Push object keys and its values to array
提问by Yasir
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
我想将每个键及其值存储到这样的 javascript 或打字稿中的数组中 [["id":23], ["name":"Jacob"], ["link":{......, ......}]] 等等
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.. which I dont know how to do as well.... how to address this issue ? thanx
我这样做是为了我可以为每个附加一个 ID,我最好的猜测是我会遍历数组并为每个附加一个 ID/一个标志......我也不知道该怎么做......如何解决这个问题 ?谢谢
回答by Salih ?enol ?akarc?
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
回答by Manos Kaparos
p.forEach( function (country) {
country.forEach( function (entry) {
entry.push( {"value" : 'Greece', "synonyms" : 'GR'});
});
});
回答by Andriy
you can try to use experimental Object.entries:
你可以尝试使用实验性的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
对于不受支持的浏览器,您可以使用 polyfill:https: //github.com/es-shims/Object.entries
回答by Andriy
You can use the Object.keysmethod to get an array of the keys, then use the Array#mapmethod to return a new array containing individual objects for each property.
您可以使用该Object.keys方法获取键的数组,然后使用该Array#map方法返回包含每个属性的单个对象的新数组。
This ES6 one-liner should do it:
这个 ES6 one-liner 应该这样做:
const splitObject = o => Object.keys(o).map(e => ({ [e]: o[e] }));
Or in ES5:
或者在 ES5 中:
function splitObject(o) {
return Object.keys(o).map(function(e) {
return Object.defineProperty({}, e, {
value: o[e],
enumerable: true
});
});
}
回答by Nina Scholz
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; }
回答by slanden
Supported in all major browser, including IE11
支持所有主流浏览器,包括 IE11
Object.entries() gives you exactly this.
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
}
}
]
]
回答by sreenath t
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*/
/* 在上面的例子中,innerobj 索引设置为 0 那么我们将把相同的数据放入 arr 如果你没有提及,那么 arr 将包含 arr[0] 我们的结果。然后我们需要像这样调用第一条记录 obj arr[0][0]*/
回答by Pramod Patil
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
您可以使用下划线

