鉴于这两个对象:
firstObject:
var firstObject = {
title: 'value1',
year: 'value2',
contributors: 'value3',
abstract: 'value4'
};
secondObject:
var secondObject = {
title: 'Title',
year: 'Year',
contributors: 'Contributors',
abstract: 'Abstract'
};
如何创建像这样结构化的第三个对象?:
var thirdObject = {
Title: 'value1'
Year: 'value2',
Contributors: 'value3',
Abstract: 'value4'
};
基本上将secondObject的属性指定为thirdObject的键,将firstObject的属性指定为thirdObject的属性。
注意:我不想要任何firstObject键的大写。
答案 0 :(得分:1)
你可以使用类似的东西:
var firstObject = {
title: 'value1',
year: 'value2',
contributors: 'value3',
abstract: 'value4'
};
var secondObject = {
title: 'Title',
year: 'Year',
contributors: 'Contributors',
abstract: 'Abstract'
};
var newObj = {};
$.each(secondObject, function(i){
newObj[this] = firstObject[i];
});
//Vanilla JS version
for(var x in secondObject){
newObj[secondObject[x]] = firstObject[x];
}
console.log(newObj);
答案 1 :(得分:0)
Example here。这个分配""如果key在firstObject中不存在。
var firstObject = {
title: 'value1',
year: 'value2',
contributors: 'value3',
abstract: 'value4'
};
var secondObject = {
title: 'Title',
year: 'Year',
contributors: 'Contributors',
abstract: 'Abstract',
extra:''
};
var thirdObject ={};
for(var key in secondObject)
{
if (secondObject.hasOwnProperty(key))
{
thirdObject[key] = (typeof firstObject[key] === "undefined")?"":firstObject[key];
}
}
console.log(thirdObject);