![](/img/trans.png)
[英]modify /change array of object keys by object keys name in javascript
[英]How to change the name of Keys and values of a javascript object
因此,我是javascript编程的新手,我需要找出一种更改键名和对象值的方法。
这是对象,我在一个名为json
的变量中:
{ 1079: "i",
1078: "h",
843: "g",
842: "f",
841: "e",
688: "d",
277: "c",
276: "b",
70: "a",
}
这是预期的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",
}
无论如何,感谢任何可以帮助我的人。
您不能在一个对象中使用相同的键,但是您可以为数组中的每个对取一个对象。
现在,由于键的对象的内部顺序可以被读取为索引,因此键的顺序现在是按数字顺序。
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; }
这将起作用。如果您正在寻找它。
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);
您可以使用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);
取一个数组,根据需要填充它:
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.