按键和值过滤数组

时间:2019-10-12 21:00:19

标签: javascript

我下面有数组对象,想用键和值进行过滤

for i in df.content:
    articleCount += 1
    for j in ngrams_count:
        count = i.count(j)
        print ("article ", articleCount, "has ", count, " instances of ngram ", j)

我想要如下输出:

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}];

3 个答案:

答案 0 :(得分:1)

假设arrayObj至少有一项,那么无论您的对象有多深,您都可以执行以下操作:

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)

答案 1 :(得分:0)

以下解决方案的工作深度可达2级。如果更深入,则必须使用递归方法。当前状态检查该值是否是创建内部循环的对象,然后将该对象缩小为所需格式

$authors_ids = get_users( array(
    'fields' => 'ID',
    'orderby'  => 'post_count',
    'order' => 'DESC',
    'who' => 'authors',
) );

答案 2 :(得分:0)

您可以将map()Object.keys()Object.values()flat()结合使用。

var arrayObj = [{ name: 'ram', lastname: 'jha', address: { firstLine: '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 } ];

var keys = Object.entries(arrayObj[0]).map(([key, value]) => {
  if (typeof value === 'object') {
    return Object.keys(value).map(subKey => key + '.' + subKey);
  } else {
    return key;
  }
}).flat();

var values = arrayObj.map(item =>
  Object.values(item).map(value =>
    typeof value === 'object' ? Object.values(value) : value
  ).flat()
);

var result = [keys].concat(values);

console.log(result);