如果对象具有来自不同数组对象键值的键,则仅返回该键

发布于 2025-01-17 08:17:23 字数 1517 浏览 0 评论 0原文

我有2个数组。

一个数组包含一些人员对象,另一个数组包含具有名称键的对象,该名称键保存人员对象所需的值。

到目前为止,我的解决方案但没有得到任何运气......

在映射人员数组时,如何仅返回人员的某​​些属性?不是整个人员对象

const customContactValues = people.map((person) => { return valuesNeeded.filter((el) => (el.name in person) ? person[el.name] : ""  ) })

console.log(customContactValues)

这是我的人员数组

    const people = [
    {
        "foods": {
            "favoriteFood": "Ice cream"
        },
        "firstName": "John",
        "lastName": "Doe",
        "age": 30

    },
    {
        "foods": {
            "favoriteFood": "pizza"
        },
        "firstName": "Jane",
        "lastName": "Doe",
        "age": 39
    },
    {
        "foods": {
            "favoriteFood": "pbj"
        },
        "firstName": "Kevin",
        "lastName": "Baker",
        "age": 22

    },
    {
        "foods": {
            "favoriteFood": "pushpops"
        },
        "firstName": "ernie",
        "lastName": "duncan",
        "age": 29
    },
]

的键,如下所示

const valuesNeeded = [ 
  { name: 'firstName' },
  { name: 'lastName' },
  { name: 'favoriteFood' }
]

这是值数组,其中包含我需要从人员数组中获取和输出

const desiredResult = [
{firstName: "John", lastName: "Doe", favoriteFood: "Ice cream"},
{firstName: "Jane", lastName: "Doe", favoriteFood: "Pizza"},
{firstName: "Kevin", lastName: "Baker", favoriteFood: "pbj"},
{firstName: "ernie", lastName: "duncan", favoriteFood: "pushpops"}
]

I have 2 arrays.

One array contains some people objects, the other array contains objects with name key that holds the value needed from the people objects.

My solution so far but not getting any luck....

When mapping over people array how do I return only certain properties from person? Not the entire person object

const customContactValues = people.map((person) => { return valuesNeeded.filter((el) => (el.name in person) ? person[el.name] : ""  ) })

console.log(customContactValues)

Here is my people array

    const people = [
    {
        "foods": {
            "favoriteFood": "Ice cream"
        },
        "firstName": "John",
        "lastName": "Doe",
        "age": 30

    },
    {
        "foods": {
            "favoriteFood": "pizza"
        },
        "firstName": "Jane",
        "lastName": "Doe",
        "age": 39
    },
    {
        "foods": {
            "favoriteFood": "pbj"
        },
        "firstName": "Kevin",
        "lastName": "Baker",
        "age": 22

    },
    {
        "foods": {
            "favoriteFood": "pushpops"
        },
        "firstName": "ernie",
        "lastName": "duncan",
        "age": 29
    },
]

Here is the values array which contains the keys I need from people array

const valuesNeeded = [ 
  { name: 'firstName' },
  { name: 'lastName' },
  { name: 'favoriteFood' }
]

I am trying to get and output like this below

const desiredResult = [
{firstName: "John", lastName: "Doe", favoriteFood: "Ice cream"},
{firstName: "Jane", lastName: "Doe", favoriteFood: "Pizza"},
{firstName: "Kevin", lastName: "Baker", favoriteFood: "pbj"},
{firstName: "ernie", lastName: "duncan", favoriteFood: "pushpops"}
]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风吹过旳痕迹 2025-01-24 08:17:23

filter 仅根据某些条件过滤数组中的元素,但在您的情况下,我们不想过滤元素,我们只想从现有数组创建新的对象数组,因此 map 功能是一个好的开始。

第二个问题是对象可以包含嵌套对象,嵌套对象可能包含所需的键值对,因此为了检索它们,如果我们没有直接在对象中找到键值,我们可以递归地查找对象的值。

由于我们不需要数组中每个对象的所有键值,因此我们可以创建一个新对象或从现有对象中删除,如果需要进一步处理,保留原始对象是一个很好且安全的选择。

const people = [{
    "foods": {
      "favoriteFood": "Ice cream"
    },
    "firstName": "John",
    "lastName": "Doe",
    "age": 30

  },
  {
    "foods": {
      "favoriteFood": "pizza"
    },
    "firstName": "Jane",
    "lastName": "Doe",
    "age": 39
  },
  {
    "foods": {
      "favoriteFood": "pbj"
    },
    "firstName": "Kevin",
    "lastName": "Baker",
    "age": 22

  },
  {
    "foods": {
      "favoriteFood": "pushpops"
    },
    "firstName": "ernie",
    "lastName": "duncan",
    "age": 29
  },
];

// function to retrieve the key value recursively
function valueByKey(obj, key) {
  let value = obj[key];
  if (value) {
    return value;
  }
  Object.keys(obj).forEach(function(k) {
    if (typeof obj[k] == 'object') {
      value = valueByKey(obj[k], key);
    }
  });
  return value;
}

const valuesNeeded = [{
    name: 'firstName'
  },
  {
    name: 'lastName'
  },
  {
    name: 'favoriteFood'
  }
];

// creating new object by passing the current object and key
let output = people.map(function(item) {
  let result = {};
  valuesNeeded.forEach(function(obj) {
    result[obj.name] = valueByKey(item, obj.name);
  });
  return result;
});

console.log(output);

filter only filters elements from array based on some condition but in your case we don't want to filter elements we just want to create new array of objects from and existing array so map function is a good start.

Second problem is the object can contain nested object which may contain required key value pair so to retrieve them we can recursively look over the value which is object if we don't find the key value directly in the object.

And since we don't want all the key value for each object in array we can either create a new object or delete from existing object, keeping the original is good and safe option if required for further processing.

const people = [{
    "foods": {
      "favoriteFood": "Ice cream"
    },
    "firstName": "John",
    "lastName": "Doe",
    "age": 30

  },
  {
    "foods": {
      "favoriteFood": "pizza"
    },
    "firstName": "Jane",
    "lastName": "Doe",
    "age": 39
  },
  {
    "foods": {
      "favoriteFood": "pbj"
    },
    "firstName": "Kevin",
    "lastName": "Baker",
    "age": 22

  },
  {
    "foods": {
      "favoriteFood": "pushpops"
    },
    "firstName": "ernie",
    "lastName": "duncan",
    "age": 29
  },
];

// function to retrieve the key value recursively
function valueByKey(obj, key) {
  let value = obj[key];
  if (value) {
    return value;
  }
  Object.keys(obj).forEach(function(k) {
    if (typeof obj[k] == 'object') {
      value = valueByKey(obj[k], key);
    }
  });
  return value;
}

const valuesNeeded = [{
    name: 'firstName'
  },
  {
    name: 'lastName'
  },
  {
    name: 'favoriteFood'
  }
];

// creating new object by passing the current object and key
let output = people.map(function(item) {
  let result = {};
  valuesNeeded.forEach(function(obj) {
    result[obj.name] = valueByKey(item, obj.name);
  });
  return result;
});

console.log(output);

冰魂雪魄 2025-01-24 08:17:23

您可以在顶层搜索所需的键,如果找不到,则转到子对象。这是我的方法:

function getValue(obj, key) {
    const keys = Object.keys(obj);
    // Check if key exist on this level
    if (keys.includes(key)) {
        return obj[key];
    } else {
        // else we try to find in child objects
        for (k of keys) {
            if (typeof obj[k] == 'object') {
                return getValue(obj[k], key);
            }
        }
    }
    //Return this if not found
    return '';
}

const people = [
    {
        foods: {
            favoriteFood: 'Ice cream',
        },
        firstName: 'John',
        lastName: 'Doe',
        age: 30,
    },
    {
        foods: {
            favoriteFood: 'pizza',
        },
        firstName: 'Jane',
        lastName: 'Doe',
        age: 39,
    },
    {
        foods: {
            favoriteFood: 'pbj',
        },
        firstName: 'Kevin',
        lastName: 'Baker',
        age: 22,
    },
    {
        foods: {
            favoriteFood: 'pushpops',
        },
        firstName: 'ernie',
        lastName: 'duncan',
        age: 29,
    },
];

const valuesNeeded = [
    { name: 'firstName' },
    { name: 'lastName' },
    { name: 'favoriteFood' },
];

let output = people.map((item) => {
    let result = {};
    valuesNeeded.forEach(function (obj) {
        result[obj.name] = getValue(item, obj.name);
    });
    return result;
});

console.log(output);

编辑1:您可以进一步将valuesNeeded简化为keysNeeded,并仅将键存储在数组中,如下所示keysNeeded = ['firatName', 'lastName', 'favoriteFood']。请相应地更改调用。

You can search for the desired key on the top level, and go to child objects if not found. Here is my approach :

function getValue(obj, key) {
    const keys = Object.keys(obj);
    // Check if key exist on this level
    if (keys.includes(key)) {
        return obj[key];
    } else {
        // else we try to find in child objects
        for (k of keys) {
            if (typeof obj[k] == 'object') {
                return getValue(obj[k], key);
            }
        }
    }
    //Return this if not found
    return '';
}

const people = [
    {
        foods: {
            favoriteFood: 'Ice cream',
        },
        firstName: 'John',
        lastName: 'Doe',
        age: 30,
    },
    {
        foods: {
            favoriteFood: 'pizza',
        },
        firstName: 'Jane',
        lastName: 'Doe',
        age: 39,
    },
    {
        foods: {
            favoriteFood: 'pbj',
        },
        firstName: 'Kevin',
        lastName: 'Baker',
        age: 22,
    },
    {
        foods: {
            favoriteFood: 'pushpops',
        },
        firstName: 'ernie',
        lastName: 'duncan',
        age: 29,
    },
];

const valuesNeeded = [
    { name: 'firstName' },
    { name: 'lastName' },
    { name: 'favoriteFood' },
];

let output = people.map((item) => {
    let result = {};
    valuesNeeded.forEach(function (obj) {
        result[obj.name] = getValue(item, obj.name);
    });
    return result;
});

console.log(output);

Edit 1 : You can further simplify valuesNeeded to keysNeeded and store only the keys in an array like this keysNeeded = ['firatName', 'lastName', 'favoriteFood']. Please change invocation accordingly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文