我想用新密钥将数组的结构更改为对象(名称:"树")
const myArray = [{"my color": "orange color", "my value":1},{"my color": "red color", "my value":2},etc];
const myObject = {name: "tree",myArray: [{"my color": "orange color", "my value":1},{"my color": "red color", "my value":2},etc]};
此功能效果不佳:
const k = Object.keys;
const myObject = k(myArray).map((k) => ({ name: "tree", myArray: myArray[k] }))
答案 0 :(得分:0)
你的回答
const myArray = [{ "my color": "orange color", "my value": 1 }, { "my color": "red color", "my value": 2 }, etc];
var myObject = new Object();
myObject.name = "tree";
myObject.myArray = myArray;
console.log(myObject);
答案 1 :(得分:0)
const myArray = [{"my color": "orange color", "my value":1},{"my color": "red color", "my value":2},etc];
const myObject = { name: "tree", myArray: myArray }
这应该可以解决问题。无需循环任何事情。
如果您需要对象的副本而不是引用,则可以使用spread operator
这是一项新的JavaScript功能,旧的浏览器不支持它。
const myArray = [{"my color": "orange color", "my value":1},{"my color": "red color", "my value":2},etc];
const myObject = { name: "tree", myArray: [ ...myArray ] }