使用键,值对替换数组中的元素

时间:2019-05-09 04:59:06

标签: javascript json

我以缩写形式列出了一个州及其相邻州的列表。遍历states.neighbors数组并返回状态的实际名称的有效方法是什么?

状态

[
  {
    "name": "Washington",
    "abbr": "WA",
    "neighbors": ["OR", "ID"]
  },
  {
    "name": "Oregon",
    "abbr": "OR",
    "neighbors": ["CA", "ID", "NV", "WA"]
  },
  {
    "name": "California",
    "abbr": "CA",
    "neighbors": ["OR", "NV", "AZ", "WA"]
  },
  ...
]

之前:

"neighbors": ["OR", "ID"]

之后:

"neighbors": ["Oregon", "Idaho"]

6 个答案:

答案 0 :(得分:4)

您可以使用find()来获取数组中与缩写相对应的元素。给定缩写ab,这将返回状态对象:

states.find(s => s.abbr == ab)

您可以将其与forEachmap()一起使用,以替换每个项目中的邻居(我已删除了不包含在列表中的州的缩写):

let states = [{"name": "Washington","abbr": "WA","neighbors": ["OR"]},{"name": "Oregon","abbr": "OR","neighbors": ["CA", "WA"]},{"name": "California","abbr": "CA","neighbors": ["OR", "WA"]},]

states.forEach(state => {
    state.neighbors = state.neighbors.map(ab => states.find(s => s.abbr == ab).name)
})

console.log(states)

理想情况下,您将为此使用对象而不是数组,这样您可以访问任何状态而不必每次都遍历数组。

答案 1 :(得分:3)

您可以找到一个代码图和邻居,例如:

const neighborsCodes = {
    "OR": "Oregon",
    "ID": "Idaho"
    // ...
}

然后迭代并替换:

// a neighbors-codes mapping
const neighborsCodes = {
    "OR": "Oregon",
    "ID": "Idaho"
    // ...
}

// your data
let array = [
    {
        "name": "Washington",
        "abbr": "WA",
        "neighbors": ["OR", "ID"]
    },
    //...
]

// iterate and replace 'neighbors' arrays elements
for (let i = 0; i < array.length; i++) {
    const element = array[i];
    for (let j = 0; j < element.neighbors.length; j++) {
        element.neighbors[j] = neighborsCodes[element.neighbors[j]];
    }
}

console.log(array);

答案 2 :(得分:2)

解决此问题的一种方法是:

  1. 创建{stateAbbr: "stateName"}的映射
  2. 将结果映射到数据中。

const data = [{
    "name": "Washington",
    "abbr": "WA",
    "neighbors": ["OR", "ID"]
  },
  {
    "name": "Oregon",
    "abbr": "OR",
    "neighbors": ["CA", "ID", "NV", "WA"]
  },
  {
    "name": "California",
    "abbr": "CA",
    "neighbors": ["OR", "NV", "AZ", "WA"]
  }
];

// create mapping
const mapping = {};
data.forEach(state => mapping[state.abbr] = state.name);

// rewrite neighbors
const neighborAbbrToName = abbr => mapping[abbr];
const result = data.map(state => ({
  ...state,
  neighbors: state.neighbors.map(neighborAbbrToName)
}));

// NOTE: incomplete data set, so will see undefined
// in the results of this example.
console.log(result);

答案 3 :(得分:2)

您可以使用abbr作为键和name作为值来创建对象。然后遍历该列表并替换每个邻居。

请参见下面的代码。如果邻居列表中的缩写在主列表中不可用,则将保留该缩写。

const data = [{
    "name": "Washington",
    "abbr": "WA",
    "neighbors": ["OR", "ID"]
  },
  {
    "name": "Oregon",
    "abbr": "OR",
    "neighbors": ["CA", "ID", "NV", "WA"]
  },
  {
    "name": "California",
    "abbr": "CA",
    "neighbors": ["OR", "NV", "AZ", "WA"]
  }
];

// First create an object with "abbr" as key and "name" as value
const states = {};
data.forEach(state => {
  states[state.abbr] = state.name;
});

// Iterate through data and update neighbours
const newData = data.map(state => {
  state.neighbors = state.neighbors.map(neighbor => states[neighbor] || neighbor)
  return state;
});

console.log(newData);

答案 4 :(得分:1)

您可以简单地使用forEach循环来迭代数组,并根据其abbr属性查找正确的状态。 请参阅下面的代码中的注释,以解释代码中发生的事情。

另一种(更有效的)方法是将一个对象映射为keyabbr,值是name属性的地方。

下面的代码段还将处理不存在的状态,并打印“未找到”默认值。

const States = [
  {
    "name": "Washington",
    "abbr": "WA",
    "neighbors": ["OR", "ID"]
  },
  {
    "name": "Oregon",
    "abbr": "OR",
    "neighbors": ["CA", "ID", "NV", "WA"]
  },
  {
    "name": "California",
    "abbr": "CA",
    "neighbors": ["OR", "NV", "AZ", "WA"]
  }
];

// Loop each state of the above array.
States.forEach(item => {
  // Map the current state's neighborhood.
  item.neighbors = item.neighbors.map(neighbor => {
    // For each neighbor, look for the first state whose "abbr" is the same as this item.
    const state = States.find(state => state.abbr === neighbor);
    // If found, return its name. Otherwise, return "Not Found".
    return state ? state.name : 'Not Found';
  });
});

console.log(States);

答案 5 :(得分:1)

我们可以先创建状态为abbr和名称的对象,然后再使用两个嵌套映射替换近邻数组。

data = [
  {
    "name": "Washington",
    "abbr": "WA",
    "neighbors": ["OR", "ID"]
  },
  {
    "name": "Oregon",
    "abbr": "OR",
    "neighbors": ["CA", "ID", "NV", "WA"]
  },
  {
    "name": "California",
    "abbr": "CA",
    "neighbors": ["OR", "NV", "AZ", "WA"]
  }
];

states = {};
// crating states object with structre {abbr:state name, abbr: state name}
data.forEach( (x) => {
    Object.assign(states, { [x.abbr]: x.name }) 
  } 
) 

// Mutating origin data neighbours array
data.map((x) => {
    return x.neighbors = x.neighbors.map((stateAbbr)=>{
        return (states[stateAbbr] == undefined) ? stateAbbr : states[stateAbbr] ;
    })
})

console.log(data)