首页 > 解决方案 > 在javascript中循环对象数组

问题描述

如何循环获取所有地址?

const name = {
  john: [
    {
      age: 21,
      address: 'LA',
    }
  ],
  sam: [
    {
      age: 26,
      address: 'California'
    }
  ]
}

我有这样的代码,但仍然卡住了流程的进展

const array = Object.entries(name);
for (let i = 0; i < array.length; i++) {
  console.log(array[i]);
}

标签: javascriptarraysloopsobject

解决方案


更新的答案

如果 ObjectValue 有多个数组。请检查下面的代码,并且我在代码之间写了一些注释。

const name = { john: [ { age: 21, address: 'LA', }, { age: 23, address: 'Franch', } ], sam: [ { age: 26, address: 'California' }, { age: 24, address: 'Swiss' } ] }

var ObjectValues = Object.values(name);


// if single user have multiple data or address apply map method to ObjectValue too

var result = ObjectValues.map((ObjectValue) => {
    return ObjectValue.map(item => item.address);
});

// try to print result before combining
// console.log(result);

// combine all child arrays into single array
result = [].concat.apply([], result);

console.log(result);

使用 forEach 循环并获取单个数组中的所有地址

const name = { john: [ { age: 21, address: 'LA', }, { age: 23, address: 'Franch', } ], sam: [ { age: 26, address: 'California' }, { age: 24, address: 'Swiss' } ] }

var ObjectValues = Object.values(name);
var result = [];

ObjectValues.forEach((ObjectValue) => {
  ObjectValue.map(item => result.push(item.address));
});

console.log(result);

只需编写一个函数以获得最佳实践

const name = { john: [ { age: 21, address: 'LA', }, { age: 23, address: 'Franch', } ], sam: [ { age: 26, address: 'California' }, { age: 24, address: 'Swiss' } ] }

console.log(getAddress(name));


function getAddress(data) {
  let result = []; // initialize storage
  
  Object.values(data).forEach(ObjectValue => {
    // store address(data)
      ObjectValue.map(item => result.push(item.address));
  });
  return result; // return data
}

旧答案

Object.entries将返回 [key, value] 对中的 Object 数组

因此,不要使用 Object.entries,而是使用 Object.values(它只会返回对象的“值”列表)

现在用 提取所有值列表后Object.values,现在只需使用maporforEach方法来获取所有地址列表

const name = {
  john: [
    {
      age: 21,
      address: 'LA',
    }
  ],
  sam: [
    {
      age: 26,
      address: 'California'
    }
  ]
}

var ObjectValues = Object.values(name);

// map method
var result = ObjectValues.map(ObjectValue => ObjectValue[0].address);
// here I have used 0 index of an ObjectValue because ObjectValue is an array of single Object of data {age, address}

console.log(result) // check result




// forEach method
var result = []

ObjectValues.forEach(ObjectValue => result.push(ObjectValue[0].address));

console.log('With forEach method (❁´◡`❁)')
console.log(result)


推荐阅读