我有一个数组:
results = [
{"Created Date ": "20181012", "Created By ": "A", "Job Number ": "001", "Department": "FS"},
{"Created Date ": "20181012", "Created By ": "B", "Job Number ": "002", "Department": "DS"},
{"Created Date ": "20181012", "Created By ": "C", "Job Number ": "004", "Department": "FS"}
]
每个值都会在以下某个时间出现。(不更改空白字符和列顺序,但列名是固定的)
results = [
{"Created By": "A", "Department": "FS", "Created Date": "20181012", "Job Number": "001" },
{"Created By": "B", "Department": "DS", "Created Date": "20181012", "Job Number": "002"},
{"Created By": "C", "Department": "FS", "Created Date": "20181012", "Job Number": "004"}
]
现在,我只想获取一个新数组,其中包含3列的值,即“创建者”,“创建日期”和“作业编号”,且具有特定顺序。期望值应为:
results = [
{"20181012", "A", "001"},
{"20181012", "B", "002"},
{"20181012", "C", "004"}
]
有什么好的解决方法吗?
答案 0 :(得分:3)
首先请注意,对象没有可靠的排序。因此,第一列或第二列没有任何意义。
但是,由于您知道要获取其值的键,因此可以使用map
并同时考虑键的两种变化来计算额外的字符:
var results = [{
"Created Date ": "20181012",
"Created By ": "A",
"Job Number ": "001",
"Department": "FS"
},
{
"Created Date": "20181012",
"Created By ": "B",
"Job Number ": "002",
"Department": "DS"
},
{
"Created Date": "20181012",
"Created By ": "C",
"Job Number ": "004",
"Department": "FS"
}
]
var output = results.map(d => [
d['Created Date'] || d['Created Date '],
d['Created By'] || d['Created By '],
d['Job Number'] || d['Job Number ']
]);
console.log(output);
答案 1 :(得分:0)
这演示了使用数组对象的map()方法的另一种方法,如下所示:
var results = [{
"Created Date ": "20181012",
"Created By ": "A",
"Job Number ": "001",
"Department": "FS"
},
{
"Created Date": "20181012",
"Created By": "B",
"Job Number": "002",
"Department": "DS"
},
{
" Created Date": "20181012",
" Created By": "C",
" Job Number": "004",
"Department": "FS"
}
];
Array.prototype.remove = function(index){
this.splice(index,1);
}
var nu_arry = results.map(item => {
let d = [];
let keys = Object.keys(item);
keys.remove(3); // remove Department key name
keys.forEach(function(key) {
d.push(item[key]);
});
return d;
});
console.log(nu_arry);
在键名之前或结尾是否存在空格都没有什么区别,因为代码可以利用Object.keys()来精确检测所有键的名称。该解决方案的优势在于,如果编码人员决定修改键的名称,由于没有对变体键进行硬编码,因此该代码仍然可以使用。注意:short arrow function语法消除了创建单独的用户定义函数的需要。