【问题标题】:Transform key/value pairs object into array of objects using Vanilla JS使用 Vanilla JS 将键/值对对象转换为对象数组
【发布时间】:2021-11-03 21:35:45
【问题描述】:

下面是我的对象

var data = {
  sku: ['1', '2', '3', '4'],
  color: [],
  season: ['winter', 'summer'],
}

下面是我期待的输出

data = [
  { sku: '1', season: 'winter'},
  { sku: '2', season: 'summer'},
  { sku: '3'},
  { sku: '4'},
]

以下是工作脚本,但不易阅读。如果您有更好的建议,请提出建议。

var data = {
  sku: ['1', '2', '3', '4'],
  color: [],
  season: ['winter', 'summer'],
}

var arr = Object.entries(data)
  .filter(item => item[1] && item[1].length) // remove empty values
  .sort((x, y) => y[1].length - x[1].length) // bring lengthy value to first

var final = arr[0][1].map((a, index) =>
  arr.reduce((b, acc) => ({
    ...b,
    ...(acc[1][index] && { [acc[0]]: acc[1][index] }),
  }), {})
);

console.log(final);

【问题讨论】:

  • “期待”哪个代码?熟悉how to access and process nested objects, arrays or JSON 以及如何使用create objects 并使用ObjectArray 的可用静态和实例方法。
  • @w3debugger ...据我所知,任何合理的尝试都会使您免于投票。但只是放弃 Q 而不表现出努力会适得其反。有些人对此非常严格。但他们大多也愿意,在 OP 相应地编辑 Q 后收回投票。
  • 确实,现在这个问题是“给我代码”。表现出你的努力会阻止这种情况。不过,有趣的是,您认为发布您的尝试会导致更多的反对票:/
  • @w3debugger ...出于好奇,您最后提供的示例代码,这是您的第一种方法吗?如果是这样,你为什么不发布它?既然它也能完成它的工作,那么你的实际问题在哪里?我唯一的建议......为自己和他人编写人类可读的代码(一个月后也可以阅读)。
  • @PeterSeliger 我知道如何得到结果,但你可以看到它不可读。这就是为什么我问是否有人可以建议更少和清晰的代码。我在发布代码后编写了代码。 AFAIK 这个平台不仅是发布完美答案的专家和发布答案的专家。看到负面印象让我真的很失望,但最终了解到大多数人的心态......顺便说一句谢谢:)

标签: javascript arrays object lodash transformation


【解决方案1】:

使用 vanilla JS,您可以使用 Array.from()Array.map() 转置(压缩)数组。然后映射数组数组,与原始键组合成对,并过滤出值为undefined 的对。之后,您可以使用 Object.fromEntries() 将对数组转换为对象:

const zip = (...arr) =>
  Array.from({ length: Math.max(...arr.map(a => a.length)) }, (_, i) => 
    arr.map(a => a[i])
  )

const createObject = obj => {
  const keys = Object.keys(obj)

  return arr => Object.fromEntries(
    keys.map((key, i) => [key, arr[i]])
      .filter(([, val]) => val !== undefined)
  )
}

const fn = obj => zip(...Object.values(obj)).map(createObject(obj))

const data = {
  sku: ['1', '2', '3', '4'],
  color: [],
  season: ['winter', 'summer'],
}

const result = fn(data)

console.log(result)

使用 lodash 将数组压缩成带有子数组的数组,每个子数组都包含一个对象的所有值。然后映射数组数组,并使用_.zipObject()将原始键与值的子数组组合到一个对象,然后将_.omit()undefined值的键组合起来。

const { omitBy, zipObject, isUndefined, zip } = _

const createObject = obj => {
  const keys = Object.keys(obj)

  return arr => omitBy(zipObject(keys, arr), isUndefined)
}

const fn = obj => zip(...Object.values(obj)).map(createObject(obj))

const data = {
  sku: ['1', '2', '3', '4'],
  color: [],
  season: ['winter', 'summer'],
}

const result = fn(data)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

【讨论】:

    【解决方案2】:

    function createListOfObjectsFromValuesConfig(config) {
      const [
    
        // the entry list with the maximum length `value` list.
        primaryEntryList,
        // the list of all remaining entry lists.
        ...listOfSecondaryEntries
    
      ] = Object
        // get an array of entries, each entry an array itself,
        // a tuple of an entry's key and value.
        .entries(config)
        // sort the array of entry arrays descending by
        // comparing the `value` array's `length`properties.
        .sort((a, b) => b[1].length - a[1].length);
    
      const [
    
        primaryKey,
        primaryValueList,
    
      ] = primaryEntryList;
    
      return primaryValueList
        .map((primaryValue, primaryIndex) => {
    
          return listOfSecondaryEntries
            .reduce((dataItem, [secondaryKey, secondaryValueList]) => {
    
              if (secondaryValueList.hasOwnProperty(primaryIndex)) {
    
                // if possible aggregate the item's
                // initially provided base data.
                Object.assign(dataItem, {
    
                  [secondaryKey]: secondaryValueList[primaryIndex]
                });
              }
              return dataItem;
    
            }, { [primaryKey]: primaryValue }); // create the item's base.
        });
    }
    
    var data = {
      sku: ['1', '2', '3', '4'],
      color: [],
      season: ['winter', 'summer'],
    };
    
    console.log(
      'createListOfObjectsFromValuesConfig(data) ...',
      createListOfObjectsFromValuesConfig(data)
    );
    .as-console-wrapper { min-height: 100%!important; top: 0; }

    【讨论】:

      猜你喜欢
      • 2016-03-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      • 2021-02-14
      相关资源
      最近更新 更多