gpt4 book ai didi

JavaScript 循环对象以将数组附加到数组

转载 作者:行者123 更新时间:2023-12-01 03:37:56 25 4
gpt4 key购买 nike

我花了一整夜的时间来研究这个问题,我知道答案很接近;但我还有很多语法工作要做。请不要对此投反对票 - 这样做只会阻止像我这样的新手提出问题。我需要创建一个接受简单对象作为参数并返回数组的函数。函数应该适用于具有任意数量的属性列和简单的字符串/数字值的对象。我将在下面附加的代码中展示并解释我的工作:

//my first code:
var hi = {a: 1, b: 2, c: 3};
var props = new Array([],[],[]);
var lent = 0;
function newWave(hi){
for(var key in hi){
props[lent].push(key);
props[lent].push(hi[key]);
lent = lent + 1;
}
return props;
}
newWave(hi);

//function yields: [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]
//The return output is correct, but I need a universal code;
//looking at the number of columns in variable 'props', you can
//tell that this function only works on objects with 3 roperties.

//My second code:
function newWave(hi) {
var props = [];
var outcome = [];
for (var i = 0; i<1; i++){
for(var key in hi){
props.push(key, hi[key]);
outcome.push(props);
}
return outcome;
}
}
newWave(hi);
//This returns:
//[ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ],
// [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ],
// [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]
//I feel like the answer is so close, but it's been 7 hours working on this,
//your help is greatly appreciated

最佳答案

function newWave (hi) {
return Object.keys(hi).map(v => [v, hi[v]]);
}

所以这里我们使用Object.keys获取对象属性的数组,然后对于每个对象属性,我们将它们映射到一个数组,该数组将属性作为第一项,其值作为第二项

关于JavaScript 循环对象以将数组附加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44115640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com