我有两个对象。如果两个对象中均出现键,则我希望第一个对象的值作为键,第二个对象的值作为值。
var obj1 = {a:"value1",b:"value2",c:"value3"}
var obj2 = {a:"index1",b:"index2",c:"index3",d:"index4"};
输出应如下所示:
{"value1":"index1","value2":"index2","value3":"index3"}
我该怎么做?
答案 0 :(得分:1)
从第一个对象获取条目([键,值]),如果键obj2
中也存在键,则使用reduce将第二个对象的值组合起来:
const obj1 = {a:"value1",b:"value2",c:"value3"};
const obj2 = {a:"index1",b:"index2",c:"index3",d:"index4"};
const result = Object.entries(obj1) // get the entries
.reduce((r, [k, v]) => {
if(k in obj2) { // if the key exists in obj2
r[v] = obj2[k]; // use the value from obj1 as the key, with the value from obj2
}
return r
}, {});
console.log(result);
使用lodash,可以从两个对象中获取密钥,并使用_.intersection()
查找公用密钥。然后,您可以使用_.at()
从每个对象获取值,并使用_.zipObject()
将两个值的数组组合到一个对象中:
const obj1 = {a:"value1",b:"value2",c:"value3"};
const obj2 = {a:"index1",b:"index2",c:"index3",d:"index4"};
// get the keys that exists in both objects
const keys = _.intersection(_.keys(obj1), _.keys(obj2));
const result = _.zipObject( // combine arrays of values to an object
_.at(obj1, keys), // get the values from obj1
_.at(obj2, keys), // get the values from obj2
)
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
答案 1 :(得分:1)
迭代 obj1 的键,并使用 obj1 的值作为键,并使用 obj2 的值作为值。
const obj1 = {a:"value1",b:"value2",c:"value3"}
const obj2 = {a:"index1",b:"index2",c:"index3",d:"index4"};
const newObj = {};
for (let key in obj1)
if (obj2[key])
newObj[obj1[key]] = obj2[key];
console.log(newObj);
答案 2 :(得分:1)
var obj1 = {a:"value1",b:"value2",c:"value3"}
var obj2 = {a:"index1",b:"index2",c:"index3",d:"index4"};
var obj = {};
for( let i in obj1) {
if(obj2.hasOwnProperty(i))
obj[ obj1[i] ] = obj2[i];
}
console.log(obj)
答案 3 :(得分:0)
var obj1 = {a:"value1",b:"value2",c:"value3"}
var obj2 = {a:"index1",b:"index2",c:"index3",d:"index4"};
/* iterate on all the props of obj1*/
const result=Object.keys(obj1).reduce((acc,obj1Prop)=>{
/*if obj2[value of propObj1] is not undefined */
if(typeof obj2[obj1Prop] !== "undefined"){
// assign the value of obj2[value of propObj1] to accumulator
acc[obj1[obj1Prop]]=obj2[obj1Prop];
}
return acc;
},{})
//result contains the result
console.log(result)