gpt4 book ai didi

javascript - 将对象数据传递给上层对象属性

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:39:08 24 4
gpt4 key购买 nike

我有一个下面的数组列表,我想从下到上分配一个值。

代码示例:

var tempArrayList=[
{org1:null,org2:"Office",org3:"HR",org4:"Payroll",org5:"Pay"},
{org1:null,org2:null,org3:"HR",org4:"Payroll",org5:"Pay"},
{org1:null,org2:"Office",org3:null,org4:null,org5:"Pay"},
{org1:null,org2:"Office",org3:"HR",org4:"Payroll",org5:"Pay"},
{org1:"head1",org2:null,org3:null,org4:"Payroll",org5:"Pay"}
];

for(var i=0;i<tempArrayList.length;i++) {
var temp=tempArrayList[i];
var org1=temp.org1;
var org2=temp.org2;
var org3=temp.org3;
var org4=temp.org4;
var org5=temp.org5;

document.write(JSON.stringify(temp));
document.writeln("<br>");
}

我的问题:如何将 org2 值设置为 org1,将 org3 值设置为 org2......

// if org1 is null then temp.org1 = temp.org2, temp.org2 = temp.org3, temp.org3 = temp.org4, temp.org4 = temp.org5

// if org1 and org2 is null then temp.org1 = temp.org3, temp.org2 = temp.org4, temp.org3 = temp.org5, temp.org4 = null

最佳答案

过滤值数组中的所有空值然后遍历键并分配过滤后的值或空值

var tempArrayList=[
{org1:null,org2:"Office",org3:"HR",org4:"Payroll",org5:"Pay"},
{org1:null,org2:null,org3:"HR",org4:"Payroll",org5:"Pay"},
{org1:null,org2:"Office",org3:null,org4:null,org5:"Pay"},
{org1:null,org2:"Office",org3:"HR",org4:"Payroll",org5:"Pay"},
{org1:"head1",org2:null,org3:null,org4:"Payroll",org5:"Pay"}
];

tempArrayList.forEach((o) => {
const vals = Object.values(o).filter(v => v);
Object.keys(o).forEach((key, i) => o[key] = vals[i] || null);
});



console.log(tempArrayList)
.as-console-wrapper {max-height:100%!important;}

关于javascript - 将对象数据传递给上层对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47445934/

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