You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将选中水果的数组对象转换为含两个拆分对象的新数组

Solution to Transform Fruit Array into Individual Value Entries

Hey there! Let's get your array transformation working the way you want it. Your current code filters out the matching fruit objects, but it doesn't split each object into separate entries with just one value property—here's how to fix that, with both Lodash and vanilla JavaScript options:

Using Lodash (since you're already using it)

This approach leverages Lodash's utilities to get the exact structure you need:

var selectFruit = document.getElementById('FiltreFruits').value;

// Step 1: Filter the source array to get only the matching fruit objects
var matchedFruits = _.filter(MyArray, { fruit: selectFruit });

// Step 2: Split each matched object into individual value entries and flatten the result
var myArrayFruitSelect = _.flatMap(matchedFruits, function(item) {
  // Remove the "fruit" key to isolate all value properties
  var valueProperties = _.omit(item, 'fruit');
  // Map each value property to a new object with the fruit name
  return _.map(valueProperties, function(value, key) {
    return { fruit: item.fruit, [key]: value };
  });
});

How this works:

  • _.filter: Grabs all objects from MyArray where the fruit matches your selected value.
  • _.flatMap: Processes each matched object, maps it to an array of new entries, then flattens the result so you don't end up with nested arrays.
  • _.omit: Strips out the fruit key from each object, leaving only the value1, value2, etc. properties.
  • _.map: Converts each remaining key-value pair into a new object that includes the original fruit name.

Using Vanilla JavaScript (no Lodash needed)

If you prefer to avoid external libraries, here's a native JS solution that does the same thing:

var selectFruit = document.getElementById('FiltreFruits').value;

var myArrayFruitSelect = MyArray
  // Filter to keep only matching fruit objects
  .filter(item => item.fruit === selectFruit)
  // Split each object into individual value entries and flatten
  .flatMap(item => {
    // Get all keys except "fruit"
    const valueKeys = Object.keys(item).filter(key => key !== 'fruit');
    // Create a new object for each value key
    return valueKeys.map(key => ({
      fruit: item.fruit,
      [key]: item[key]
    }));
  });

Result Example

When selectFruit is "Apple", both solutions will produce:

[
  { fruit: "Apple", value1: 89 },
  { fruit: "Apple", value2: 2.6 }
]

内容的提问来源于stack exchange,提问作者observatoire

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:06:24