简体   繁体   English

javascript转换 <string, string[]> 至 <string, string>

[英]javascript convert <string, string[]> to <string, string>

I have a javascript object with key/value pairs where the value is an array of strings: 我有一个带有键/值对的javascript对象,其中值是一个字符串数组:

var errors = {
    "Message": ["Error #1", "Error #2"],
    "Email": ["Error #3", "Error #4"]
};

I would like to convert this to a key/value pair with the first element of each array so that it is a instead of : 我想将其转换为每个数组的第一个元素的键/值对,以便它是一个而不是:

var firstErrorOnly = {
    "Message": "Error #1",
    "Email": "Error #3"
};

I tried doing this using jQuery.map but I was not getting the results I wanted. 我尝试使用jQuery.map进行此操作,但未获得所需的结果。 How can I accomplish this? 我该怎么做?

You can traverse the whole object using for ... in and hasOwnProperty() to create a new object in the style you wish. 您可以使用for ... inhasOwnProperty()遍历整个对象,以for ... in的样式创建一个新对象。

var firstErrorOnly = {};
for( var key in errors ) {
  if ( errors.hasOwnProperty( key ) ) {
    firstErrorOnly[ key ] = errors[key][0];
  }
}

For a jQuery implementation, try this: 对于jQuery实现,请尝试以下操作:

var firstErrorOnly = {};
$.each(errors, function(i, value) {
    firstErrorOnly[i] = value[0];
});

Example fiddle 小提琴的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM