获取数组中键的所有对象值

时间:2020-07-21 17:27:45

标签: javascript vuejs2 javascript-objects

我有一个这样的对象:

myObj = { 1:{name:'a'}, 2:{name:'v'}, 3:{name:'x'}, 10:{name:'t'} };

并且我想要获取其键在以下列表中的值的列表:

myList = [1,2,10]

所以我想要的结果是:

[{name:'a'},{name:'v'}, {name:'t'}]

关于如何做到这一点的任何想法?

我尝试了以下操作:

const result = [];
        
for (const childId in state.frameObjects[id].childrenIds ) 
{
     if(state.frameObjects[childId]!==undefined)
     {
          result.push(state.frameObjects[childId]);
     }
}
        
return result;

但是Vue控制台给了我这个错误: 内部错误:“递归过多”

11 个答案:

答案 0 :(得分:1)

您可以将所需的密钥放入Set中并使用filter。如果数组包含对象中不存在的键,这也将起作用。

const myObj = { 1:{name:'a'}, 2:{name:'v'}, 3:{name:'x'}, 10:{name:'t'} };
const keys = new Set([1,2,10])
const res = Object.keys(myObj).filter(key=>keys.has(+key)).map(key=>myObj[key]);
console.log(res);

答案 1 :(得分:0)

您可以这样操作:

var objectArray = [];
myList.forEach(function(key){
    if(myObj[key]){ 
       objectArray.push(myObj[key]);
     }
});

答案 2 :(得分:0)

您可以使用键迭代数组,并检查它们是否存在于height中,然后可以将值压入新的arrya中:

.wrapper

答案 3 :(得分:0)

这可以通过几种方法完成; 一种选择是遍历对象属性

//your response
var data = [{
    tipo: "O",
    numero: "001",
    data: {
      year: 2019,
      month: 4,
      day: 18
    },
    prazo: 1,
    documento: "4600530888"
  },
  {
    tipo: "O",
    numero: "001",
    data: {
      year: 2009,
      month: 4,
      day: 18
    },
    prazo: 0,
    documento: "4600530588"
  }
]
var indices = ['Tipo', 'Numero', 'Document', 'Prazo','Data']
var table = $("<table border='1'>")
var thead = $('<thead>')
for (const index of indices) {

  $('<th>' + index + '</th>').appendTo(thead)
}
var tbody = $('<tbody>')
for (const item of data) {
  var tr = $('<tr>')
  //get datas from json 
  $('<td>' + item.tipo + '</td>').appendTo(tr)
  $('<td>' + item.numero + '</td>').appendTo(tr)
  $('<td>' + item.prazo + '</td>').appendTo(tr)
  $('<td>' + item.documento + '</td>').appendTo(tr)
   $("<td>" + item.data.year + "/" + item.data.month + "/" + item.data.day + "</td>").appendTo(tr)
    tr.appendTo(tbody)

}
//apend data in thead 
thead.appendTo(table)
tbody.appendTo(table)

$("#loaderMaiorDemandante").hide();
table.appendTo('#records_table')

使用Object.keys()可以达到相同的结果

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="records_table"></div>

答案 4 :(得分:0)

只需要map

var myObj = { 1:{name:'a'}, 2:{name:'v'}, 3:{name:'x'}, 10:{name:'t'} };
var myList = [1,2,10]
// var result = myList.map( function(k){ return myObj[k]; })
var result = myList.map( k => myObj[k])

console.log(result);

如果有人说它可能不在列表中,请使用filter

var myObj = { 1:{name:'a'}, 2:{name:'v'}, 3:{name:'x'}, 10:{name:'t'} };
var myList = [1,2,10, 33, 44, 555]
// var result = myList.map( function(k){ return myObj[k]; }).filter(function(o) { return o; });
var result = myList.map( k => myObj[k]).filter(Boolean);

console.log(result);

或使用reduce进行一次循环

var myObj = { 1:{name:'a'}, 2:{name:'v'}, 3:{name:'x'}, 10:{name:'t'} };
var myList = [1,2,10, 33, 44, 555]
var result = myList.reduce((a, k) =>
  (myObj[k] && a.push(myObj[k]), a), [])
// var result = myList.reduce(function(a, k) {
//  if(myObj[k]) { 
//     a.push(myObj[k]);
//   }
//   return a
// }, []);
console.log(result);

答案 5 :(得分:0)

您可以过滤它们对象的键,然后映射结果。

const valuesOf = (obj, keys) => Object.keys(obj)
  .filter(key => keys.includes(parseInt(key, 10)))
  .map(key => obj[key])

const myObj = { 1: { name: 'a'}, 2: { name: 'v'}, 3: { name: 'x'}, 10: { name: 't'} };

console.log(valuesOf(myObj, [1, 2, 10]))
.as-console-wrapper { top: 0; min-height: 100% }

或者,您以后可以尝试映射和过滤。这使您可以按所需键的顺序返回对象。

const valuesOf = (obj, keys) =>
  keys.map(key => obj[key]).filter(v => v !== undefined)

const myObj = { 1: { name: 'a'}, 2: { name: 'v'}, 3: { name: 'x'}, 10: { name: 't'} };

console.log(valuesOf(myObj, [1, 2, 10]))
.as-console-wrapper { top: 0; min-height: 100% }

答案 6 :(得分:0)

更实用的方法是:myList.map(a => myObj[a]).filter(a => a)

注意:.filter(a => a)将删除undefined

答案 7 :(得分:0)

尝试

let myObj = { 1:{name:'a'}, 2:{name:'v'}, 3:{name:'x'}, 10:{name:'t'} };
    let objsArray = []
    let myList = [1,2,10];
    for (let index = 0; index < myList.length; index++) {
       const element = myList[index];
       objsArray.push(myObj[element])
  
    }
    
    console.log(objsArray)

答案 8 :(得分:0)

const myObj = { 1:{name:'a'}, 2:{name:'v'}, 3:{name:'x'}, 10:{name:'t'} };
const myList = [1,2,10];

const result = myList?.map(key => (myObj == null ? null : myObj[key]), []) || [];
console.log(result);

答案 9 :(得分:0)

使用Map

 myObj = { 1:{name:'a'}, 2:{name:'v'}, 3:{name:'x'}, 10:{name:'t'} };
 myList = [1,2,10]
 map= new Map(),res=[]
 Object.entries(myObj).map(o=>map.set(o[0],o[1]))
 myList.forEach(o=>{ v=map.get(o.toString())
   if(v) res.push(v)})
 console.log(res)

答案 10 :(得分:0)

这就是您想要的:

const myObj = { 1:{name:'a'}, 2:{name:'v'}, 3:{name:'x'}, 10:{name:'t'} };

const myList = [1,2,10];

const res = Object.entries(myObj).filter(([k,v])=>{
  return myList.includes(+k);
}).map(([k,v])=>{
  return v;
})
console.log(res);//[{name:'a'},{name:'v'}, {name:'t'}]