我有以下数组对象,想要使用键和值进行过滤
var arrayObj = [{name:'ram',lastname:'jha',address:{fistLine:'100 ft raod',street:'kfc'},mobileNumber:12345745},
{name:'rakesh',lastname:'jha',address:{fistLine:'200 ft raod',street:'pizza hut'},mobileNumber:12345746},
{name:'pankaj',lastname:'jha',address:{fistLine:'300 ft raod',street:'abc line'},mobileNumber:12345747}];
我想要如下输出:
let newarrayObj:[['name','lastname', 'address.fistLine','address.street','mobileNumber'],
['ram','jha','100 ft raod','kfc','12345745'],
['rakesh','jha','200 ft raod','pizza hut','12345746'],
['pankaj','jha','300 ft raod','abc line','12345747']]
最佳答案
假设 arrayObj 至少有 1 个项目,无论您的对象有多深,您都可以执行以下操作:
const flatKeys = object => Object.entries(object).reduce((keys, [key, value]) => {
if (typeof value === 'object') { // && value !== null if needed
flatKeys(value).forEach(subKey => keys.push(key + '.' + subKey))
} else {
keys.push(key)
}
return keys
}, [])
const flatValues = object => Object.values(object).reduce((values, value) => {
if (typeof value === 'object') { // && value !== null if needed
flatValues(value).forEach(subValue => values.push(subValue))
} else {
values.push(value)
}
return values
}, [])
const arrayObj = [
{ name: 'ram', lastname:'jha', address: { fistLine:'100 ft raod', street: 'kfc' }, mobileNumber: 12345745 },
{ name: 'rakesh', lastname:'jha', address: { fistLine:'200 ft raod', street: 'pizza hut' }, mobileNumber: 12345746 },
{ name: 'pankaj', lastname:'jha', address: { fistLine:'300 ft raod', street: 'abc line' }, mobileNumber: 12345747 }
]
const newarrayObj = [flatKeys(arrayObj[0]), ...arrayObj.map(flatValues)]
console.log(newarrayObj)
关于javascript - 按键和值过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58358467/