Javascript。将对象添加到数组的特定索引中

问题描述 投票:0回答:1

我有一个Objects数组,我想把它添加到一个特定的索引中,而且只有当它是 visible:true 在另一个数组中。

我已经尝试了以下代码。

let arrVal = []

let arr = [
{ id:456,indexValue:2,isVisible:true},
{ name:"xyz",indexValue:3,isVisible:true},
{ age:21,indexValue:5,isVisible:true},
{ gender:"male",indexValue:1,isVisible:false},
{ city:"new york",indexValue:0,isVisible:false},
{ country:"usa",indexValue:4,isVisible:true}

]

for (let index = 0; index < arr.length; index++) {
                const element = arr[index];
                if(element.isVisible === true){
                  arrVal.splice(element.indexValue,0,element)
                }
            }
            
console.log("Values : " , arrVal)

任何帮助将是巨大的。

谢谢你的帮助。

javascript arrays object
1个回答
0
投票

基于 本回答 对结果数组进行单行排序。

arrVal.sort((a,b) => (a.indexValue > b.indexValue) ? 1 : ((b.indexValue> a.indexValue) ? -1 : 0)); 
© www.soinside.com 2019 - 2024. All rights reserved.