Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

Check for matching key in array, if found take 2nd array entries if not take 1st array entries in javascript

Im having 2 array object

1.

itemMapping = {
    id:1,
    hierarchyDesc:"Men's casual",
    style:"Denim Pants",
    styleDesc:"VS pants",
    color:"blue"
}
mapData = {
    hierarchyDesc:"Women's casual",
    style:"Cotton Pants",
    styleDesc:"pants"
}

I need to compare each itemMapping's key with each mapData's key and form an newArray, if any of keys are matching, (for ex: here in itemMapping and mapData - hierarchyDesc, style, styleDesc are there in both) then take those matching objects entries from mapData array and push to newArray, if its not matching and is only in itemMapping array then take those not matching object entries from itemMapping array and push to newArray.

Note: all the object key of mapData will be present in itemMapping but vice versa is not true.

expected result:

newArray = {
    id:1,
    hierarchyDesc:"Women's casual",
    style:"Cotton Pants",
    styleDesc:"pants",
    color:"blue"
}

how can I achieve it in Javascript?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use ES6 spread operator const res = {...itemMapping, ...mapData }

See below

const itemMapping = { id:1, hierarchyDesc:"Men's casual", style:"Denim Pants", styleDesc:"VS pants", color:"blue" },
mapData = { hierarchyDesc:"Women's casual", style:"Cotton Pants", styleDesc:"pants" };
const res = {...itemMapping, ...mapData  }
console.log(res);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...