我如何使数组值的上半部分成为钥匙,而另一半成为这些键的值?

发布于 2025-01-25 18:25:56 字数 1455 浏览 1 评论 0原文

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

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

发布评论

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

评论(2

秋意浓 2025-02-01 18:25:56

您可以使用 code> array.prototype。 flatmap

const flatMapToEntry = (key, index, array) => {
  const length = array.length / 2;
  if (index >= length) {
    return [];
  }
  const value = array[index + length];
  return [{ [key]: value }];
};
const result = array.map(o => o.value).flatMap(flapMapToEntry);

You can use Array.prototype.flatMap:

const flatMapToEntry = (key, index, array) => {
  const length = array.length / 2;
  if (index >= length) {
    return [];
  }
  const value = array[index + length];
  return [{ [key]: value }];
};
const result = array.map(o => o.value).flatMap(flapMapToEntry);
诠释孤独 2025-02-01 18:25:56

这是使用评论中提供的相同逻辑的答案。这具有相关的描述以帮助更好地理解。

const getMyObject = arr => {
// first compuate the half-length "lenBy2" of given array
const lenBy2 = Math.floor(arr.length / 2);

// return the "result" as an object
return Object
.fromEntries( // generate object from key-value pairs below
arr.map( // iterate "arr" to obtain key-value pairs
({ value }, idx) => ( // get the index "idx" and de-structure to access "value"
idx < lenBy2 // if index less than half-length "lenBy2"
? [ // return key-value pair as a 2-element array
value, // [ "banana", "yellow" ], for example
arr[idx + lenBy2]?.value
]
: [] // if index >= half-length, return empty array
)
).filter( // filter key-value pairs to retain only non-empty ones
x => x.length == 2
)
);
};

// below are steps only to generate results for various test cases
// the original array from the question
const array1 = [{value: 'banana'}, {value: 'apple'}, {value: 'yellow'}, {value: 'red'}];

// test-case 2 - an array with 3 pairs
const array2 = [
{value: 'banana'}, {value: 'apple'}, {value: 'tomato'},
{value: 'yellow'}, {value: 'green'}, {value: 'red'}
];

// mismatched array where the fruit "orange" has no matching color
const array3 = [
{value: 'banana'}, {value: 'apple'}, {value: 'orange'},
{value: 'yellow'}, {value: 'red'}
];

// mismatched array where the color "orange" has no matching fruit
const array4 = [
{value: 'banana'}, {value: 'apple'},
{value: 'yellow'}, {value: 'red'}, {value: 'orange'}
];

// iterate over the various test case arrays &
// console.log the result
[array1, array2, array3, array4].forEach((arr, idx) =>
console.log(
`\n***---> test case ${idx + 1} <---***\n`,
'given array:

Here is an answer using the same logic provided in the comment. This has relevant descriptions to help understand better.

const getMyObject = arr => {
  // first compuate the half-length "lenBy2" of given array
  const lenBy2 = Math.floor(arr.length / 2);
  
  // return the "result" as an object
  return Object
    .fromEntries(                 // generate object from key-value pairs below
      arr.map(                    // iterate "arr" to obtain key-value pairs
        ({ value }, idx) => (     // get the index "idx" and de-structure to access "value"
          idx < lenBy2            // if index less than half-length "lenBy2"
          ? [                     // return key-value pair as a 2-element array
            value,                // [ "banana", "yellow" ], for example
            arr[idx + lenBy2]?.value
          ]
          : []                    // if index >= half-length, return empty array
        )
      ).filter(                   // filter key-value pairs to retain only non-empty ones
        x => x.length == 2
      )
    );
};

// below are steps only to generate results for various test cases
// the original array from the question
const array1 = [{value: 'banana'}, {value: 'apple'}, {value: 'yellow'}, {value: 'red'}];

// test-case 2 - an array with 3 pairs
const array2 = [
  {value: 'banana'}, {value: 'apple'}, {value: 'tomato'},
  {value: 'yellow'}, {value: 'green'}, {value: 'red'}
];

// mismatched array where the fruit "orange" has no matching color
const array3 = [
  {value: 'banana'}, {value: 'apple'}, {value: 'orange'},
  {value: 'yellow'}, {value: 'red'}
];

// mismatched array where the color "orange" has no matching fruit
const array4 = [
  {value: 'banana'}, {value: 'apple'},
  {value: 'yellow'}, {value: 'red'}, {value: 'orange'}
];

// iterate over the various test case arrays &
// console.log the result
[array1, array2, array3, array4].forEach((arr, idx) =>
  console.log(
    `\n***---> test case ${idx + 1} <---***\n`,
    'given array: ???? ', JSON.stringify(arr),
    '\n\nresult object: ???? \n', getMyObject(arr),
    '\n ***---> end of result <---*** \n\n'
  )
);
.as-console-wrapper { max-height: 100% !important; top: 0 }

Feel free to post questions in comments, in case it is unclear how the above works.

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