如何从一个数组中获取代码并从另一个数组中查找值并返回新值

时间:2019-03-01 10:34:52

标签: javascript arrays

我有一组提供代码的数据-我从API调用中获得了这些数据。使用此代码,我需要查找从另一个数组和API调用获得的值。
然后,我需要返回这个新值。
我最初有一个switch语句,我对其进行了硬编码-但这不能伸缩,因为返回值将更改。我基本上是在映射原始数组,然后在此映射中,我需要遍历另一个数组并返回新值。

  const data = 
[{name: "youtube",  type: "v"},{name: "photo", type: "i"}]

const codes = [{code:"v", description:"video"},{code:"i", description:"image"}]

所以我需要做这样的事情,但这是行不通的,它只适用于一个值

data.map((item, index) => {
  const newList = codes.reduce((pre, curr) => {
    if (curr.code === item.type) {
      return curr
    }
  })
  return { ...item, ...item.type = newList.description }
})

因此,新数组的预期结果将是

[{name: "youtube",  type: "video"},{name: "photo", type: "image"}]

3 个答案:

答案 0 :(得分:1)

您可以使用mapfind

做类似的事情

const data = [{name: "youtube",  type: "v"},{name: "photo", type: "i"}]
const codes = [{code:"v", description:"video"},{code:"i", description:"image"}]

const newData = data.map(item => {
  const code = codes.find(b => b.code === item.type);
  return { ...item, type: code.description }
})

console.log(newData)

您还可以使用codetypereduce创建映射对象。

{
  "v": "video",
  "i": "image"
}

然后在codeMap[d.type]内使用map来获取description。这样,您可以避免使用find

重复获取相同的数据

const data = [{name: "youtube",  type: "v"},{name: "photo", type: "i"}]
const codes = [{code:"v", description:"video"},{code:"i", description:"image"}]

const codeMap = codes.reduce((acc, c) => (acc[c.code] = c.description, acc), {})
const newData = data.map(d => ({ ...d, type: codeMap[d.type] }))

console.log(codeMap)
console.log(newData)

答案 1 :(得分:1)

在此处使用find代替reduce

const data = [{name: "youtube",  type: "v"},{name: "photo", type: "i"}];
const codes = [{code:'v', description:'video'},{code:'i', description:'image'}];

// `map` over data destructing the type (and all the other properties)
const out = data.map(({ type, ...rest }) => {

  // Destructure the description from the
  // matching object in the codes array
  const { description } = codes.find(obj => obj.code === type);

  // Return the new object
  return { ...rest, type: description };
});

console.log(out);

答案 2 :(得分:0)

您还可以使用以下代码获得所需的结果

var data = [{name: "youtube",  type: "v"},{name: "photo", type: "i"}]

var codes = [{code:"v", description:"video"},{code:"i", 
description:"image"}]
/*Create a Map of the codes and what it means basically convert the codes 
array to a key,value map*/

var codeMap = {};

codes.map(item => {
 codeMap[item['code']] = item['description']
})

var finalResult = []

data.map(item => {
finalResult.push({name:item.name,type:codeMap[item.type]})
})
console.log(finalResult)