最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using key, value pairs to replace elements in an array - Stack Overflow

programmeradmin0浏览0评论

I have a list of states and their neighboring states listed in abbreviation form. What is an efficient way of iterating over the states.neighbors array and returning the actual name of the states?

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"]
  },
  ...
]

Before:

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

After:

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

I have a list of states and their neighboring states listed in abbreviation form. What is an efficient way of iterating over the states.neighbors array and returning the actual name of the states?

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"]
  },
  ...
]

Before:

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

After:

"neighbors": ["Oregon", "Idaho"]
Share Improve this question edited May 9, 2019 at 5:20 O P asked May 9, 2019 at 4:59 O PO P 2,36511 gold badges42 silver badges75 bronze badges 1
  • Use find() to find the element in the list matching the abbreviation. – Mark Commented May 9, 2019 at 5:02
Add a ment  | 

6 Answers 6

Reset to default 4

You can use find() to get the element in the array corresponding to the abbreviation. Given an abbreviation ab, this will return the state object:

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

You can use that with forEach and map() to replace the neighbors in each item (I've removed the abbreviation for states not int the list):

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)

Ideally you would use an object for this rather than an array so you could access any state without having to loop over the array each time.

You could have a map of codes and neighbors like:

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

Then iterate and replace:

// 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);

You can create an object with the abbr as key and the name as value. Then iterate through the list and replace each neighbour.

See the code below. If an abbreviation in the neighbour list is not available in the main list, the abbreviation will be retained.

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);

One way to solve this is to:

  1. create a mapping of {stateAbbr: "stateName"}
  2. map the results into the data.

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: inplete data set, so will see undefined
// in the results of this example.
console.log(result);

You can simply use a forEach loop to iterate the array and look up for the correct state upon its abbr property. See the ments in the code below explaining what is happening on the code.

Another possible (more efficient) approach would be to map an object where they key is the abbr, and the value is the name property.

The below snippet will take care of non-existing states as well, printing a "Not Found" default value.

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);

We can do this by first creating object of state abbr and name, After that we can replace the neighbors array using two nested mapping.

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)

发布评论

评论列表(0)

  1. 暂无评论