简体   繁体   English

如何更改键名称和javascript对象的值

[英]How to change the name of Keys and values of a javascript object

So, I'm new to javascript programming and I need to figure it out a way to change the name of keys and values of an object. 因此,我是javascript编程的新手,我需要找出一种更改键名和对象值的方法。

Here's the object, I'ts in a variable called json : 这是对象,我在一个名为json的变量中:

{ 1079: "i",
  1078: "h", 
  843: "g", 
  842: "f",
  841: "e", 
  688: "d",  
  277: "c",
  276: "b",
  70: "a",
}

This is the expected console.log : 这是预期的console.log

{ name: 1079 value: "i",
   name: 1078: value: "h", 
   name: 843: value:"g", 
   name: 842: value:"f",
   name: 841: value:"e", 
   name: 688: value:"d",  
   name: 277: value:"c",
   name: 276: value:"b",
   name: 70: value:"a",
}

Anyway, thanks to anyone that can help me. 无论如何,感谢任何可以帮助我的人。

You can not have the same key in an object, but you could take single objects for each pair in an array. 您不能在一个对象中使用相同的键,但是您可以为数组中的每个对取一个对象。

The order is now by the key in numerical order, because of the internal ordering of objects with keys who could be read as indices. 现在,由于键的对象的内部顺序可以被读取为索引,因此键的顺序现在是按数字顺序。

 var object = { 1079: "i", 1078: "h", 843: "g", 842: "f", 841: "e", 688: "d", 277: "c", 276: "b", 70: "a" }, result = Object.entries(object).map(([name, value]) => ({ name, value })); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

This will work .If you are looking for this. 这将起作用。如果您正在寻找它。

 let obj = { 1079: "i", 1078: "h", 843: "g", 842: "f", 841: "e", 688: "d", 277: "c", 276: "b", 70: "a", } let result = Object.entries(obj).reduce((acc, [name, value]) => { acc.push({ name, value }) return acc; }, []) console.log(result) 

    var currentObj = { 1079: "i",
      1078: "h", 
      843: "g", 
      842: "f",
      841: "e", 
      688: "d",

      277: "c",
      276: "b",
      70: "a",
    };

    var newObj = Object.keys(currentObj).map(x => { return { name: x, value: currentObj[x] };});
console.log(newObj);

You can use Object.entries() 您可以使用Object.entries()

 const data = { 1079: "i", 1078: "h", 843: "g", 842: "f", 841: "e", 688: "d", 277: "c", 276: "b", 70: "a", }; function formatObject(obj) { const arr = []; Object.entries(obj).forEach(x => { arr.push({ name: x[0], value: x[1] }); }); return arr; } const result = formatObject(data); console.log(result); 

Take an array, populate it like you want: 取一个数组,根据需要填充它:

 var json = { 1079: "i", 1078: "h", 843: "g", 842: "f", 841: "e", 688: "d", 277: "c", 276: "b", 70: "a" } var arr = []; for(k in json) arr.push({name:k, value:json[k]}) console.log(arr) 

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

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