简体   繁体   English

如何将每个对象插入密钥对值

[英]How can I insert each object into key pair value

I have a object like where I declear some properties and value. 我有一个对象,例如我在其中清除一些属性和值的对象。

var obj = {
    "country" : "USA",
    "CApital" : "WDC",
    "President" : "Trump"
}

Now I am adding in this way, I make one id and in that id I want to add my object property and values. 现在,我以这种方式添加一个ID,然后我要添加我的对象属性和值。

var myId =  obj.President;

this.newObj[myId] = {};

Object.each(obj, function(key, value) {
    this.newObj[myId][key] = value;
});

My output shoud be 我的输出应该是

obj :{
    Trump :{
        "country" : "USA",
        "CApital" : "WDC",
        "President" : "Trump"
    }
}

There is no such thing as Object.each. 没有诸如Object.each这样的东西。

Simplest is use Object.assign() to merge copy of original object to new object 最简单的方法是使用Object.assign()将原始对象的副本合并到新对象

 let obj = { "country" : "USA", "CApital" : "WDC", "President" : "Trump" } let newObj= {[obj.President] : Object.assign({}, obj)} console.log(newObj) 

I understood you want to create a new object with a property value equals to source object identifier evaluation, and inside that property goes the initial object. 我知道您想创建一个属性值等于源对象标识符评估的新对象,并且该属性内包含初始对象。 Something like this: 像这样:

 const obj = { country: 'usa', capital: 'dc', president: 'trump' }; function myPropAndObjectValues(obj, prop) { return { [obj[prop]]: {...obj} }; } console.log(myPropAndObjectValues(obj, 'president')); 

Pd. Object.each doesn't exist. Object.each不存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM