Suppose if we are having data like this, how can we use dot notations or anything to update the array(data2) inside the object data1 which is inside the array(data).
data = [
data1:
{
a:"1",
b:"2"
}
]
// another array(data2 - below) I am having I have to push that array inside
data1 as an object
data2 = [
{
c:"3"
},
{
d:"4"
}
]
The response I want as below:
data = [
data1:
{
a:"1",
b:"2"
},
data2 = [
{
c:"3"
},
{
d:"4"
}
]
]
var array = [];
array['data1'] = { 'name': 'a' }
var array2 = [{ c: 3 }, { d: 4 }];
array['data2'] = array2;
console.log(array)
OutPut:
[ data1: { name: 'a' }, data2: [ { c: 3 }, { d: 4 } ] ]
I didnt really understand your question but i think this is what you want?!
data = {
data1:
{
a: "1",
b: "2"
}
}
data2 = [
{
c: "3"
},
{
a: "3"
},
{
d: "4"
}
]
for (var key in data2) {
for (var key2 in data2[key]) {
if(data.data1[key2] != null){
console.log("data.data1 with they key" + key2 + " could have been replaced/updated with " + data2[key][key2]);
}
console.log("key " + key2 + " has value " + data2[key][key2]);
}
}
Result:
key c has value 3
data.data1 with they keya could have been replaced/updated with 3
key a has value 3
key d has value 4
Edit:
Why dont you just do
data["data2"] = data2?
I tried on myself and I got the solution. If we have to make another field in an object you just give a name like this
data.dataTwo
this will create another field with new name and now if we want to transfer or store an array in this we can simply do this
data.dataTwo = data2
This will assign that data2 named array in a new field what is given as dataTwo
I have to create match condition based on an array my array will look like below
var groupData={
A:[
{rollnum: 1, name:'Arya', age:15},
{rollnum: 2, name:'Aryan', age:15}
],
B:[
{rollnum:11, name:'Biba', age:15},
{rollnum:12, name:'Bimisha', age:15}
]
}
I am looping using for loop. How can reduce the loops. Can any one suggest me a proper way for this
Object.values(groupData).flat().forEach((rowitem)=>{
query={};
Object.keys(rowitem).forEach(eachField=>{
query[eachField]["$in"].push(rowitem[eachField])
});
fullarray[Object.keys(groupData)]=matchQuery;
})
I need an output (fullarray) like below
{
'A':{
rollnum:{'$in':[1,2]},
name: {'$in':['Arya', 'Aryan']},
age: {'$in':[15]}
},
'B':{
rollnum:{'$in':[11,12]},
name: {'$in':['Biba', 'Bimisha']},
age: {'$in':[15]}
}
}
Here 'A' 'B' is not coming correctly
Don't use Object.values() since that discards the A and B keys.
Use nested loops, one loop for the properties in the object, and a nested loop for the arrays.
You need to create the nested objects and arrays before you can add to them.
var groupData = { A:
[ { rollnum: 1,
name: 'Arya',
age:15},
{ rollnum: 2,
name: 'Aryan',
age:15}, ],
B:
[ { rollnum: 11,
name: 'Biba',
age:15},
{ rollnum: 12,
name: 'Bimisha',
age:15} ] }
result = {};
Object.entries(groupData).forEach(([key, arr]) => {
if (!result[key]) {
result[key] = {};
}
cur = result[key];
arr.forEach(obj => {
Object.entries(obj).forEach(([key2, val]) => {
if (!cur[key2]) {
cur[key2] = {
"$in": []
};
}
cur[key2]["$in"].push(val);
});
});
});
console.log(result);
I am new to JS and I am trying to do a basic operation on a JS object.
I have the following object:
var originalObj = {
id: 1,
name: 'originalObj'
}
Now I would like to add another object as a field to originalObj.
var newObj = {
newId: 2,
name: 'newObj'
}
So expected outcome is:
orginalObj = {
id: 1,
name: 'originalObj',
newObj: {
newId: 2,
name: 'newObj'
}
}
What I tried so far:
originalObj.newObj = newObj and originalObj['newObj'] = newObj
This results in:
orginalObj = {
id: 1,
name: 'originalObj',
newObj:
}
Object.assign(originalObj, newObj)
This add all the fields of newObj on the same level as originalObj. Like below:
originalObj = {
id: 1,
name: 'originalObj',
newId: 2,
name: 'newObj'
}
Depends on if you want a deep copy or just a reference.
originalObj.newObj = newObj; will assign a reference to newObj where as
originalObj.newObj = Object.assign({}, newObj); will create a new one.
Note: if your using ECMAScript 2015 (6th Edition, ECMA-262) you can use the spread operator ...
originalObj.newObj = {...newObj};
Example: https://jsbin.com/yisiyip/edit?js,console
originalObj.newObj=newObj; //this should do the job
const originalObj = {
id: 1,
name: 'originalObj'
}
const newObj = {
newId: 2,
name: 'newObj'
}
originalObj = { ...originalObj, newObj }
what's happening here is you are spreading the values of originalObj into an empty object together with the value of newObj by shorthand method
reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer
I'm trying to get my head around map functions.
Here is my working code and output using a nested for loop:
var jsonsToAddTo = [
{'cat':'k1','key2':'a'},
{'cat':'k1','key2':'b'},
{'cat':'k2','key2':'a'},
{'cat':'k2','key2':'b'},
{'cat':'k3','key2':'a'}
]
var additionalData = [
{'pk':'k1','key3':'data1'},
{'pk':'k2','key3':'data2'},
{'pk':'k3','key3':'data3'},
]
// Adds a key value pair from sourceJson to targetJson based on a matching value
function denormalizeJsonOnKey(targetJsonArray,targetKeyToMatch, sourceJsonArray, sourceKeyToMatch, keyToAdd){
for(thisJson in targetJsonArray){
for(thatJson in sourceJsonArray){
if(targetJsonArray[thisJson][targetKeyToMatch]==sourceJsonArray[thatJson][sourceKeyToMatch]){
console.log('match');
targetJsonArray[thisJson][keyToAdd]=sourceJsonArray[thatJson][keyToAdd];
}
}
}
return targetJsonArray
}
console.log(denormalizeJsonOnKey(jsonsToAddTo,'cat',additionalData,'pk','key3'))
OUTPUT:
[
{ cat: 'k1', key2: 'a', key3: 'data1' },
{ cat: 'k1', key2: 'b', key3: 'data1' },
{ cat: 'k2', key2: 'a', key3: 'data2' },
{ cat: 'k2', key2: 'b', key3: 'data2' },
{ cat: 'k3', key2: 'a', key3: 'data3' }
]
I can't figure out how to handle the nesting using a map function on an array.
Using ES6 can simplify using Array#find() and Object#assign()
var data = [
{'cat':'k1','key2':'a'},
{'cat':'k1','key2':'b'},
{'cat':'k2','key2':'a'},
{'cat':'k2','key2':'b'},
{'cat':'k3','key2':'a'}
]
var data2 = [
{'pk':'k1','key3':'data1'},
{'pk':'k2','key3':'data2'},
{'pk':'k3','key3':'data3'},
]
const mergeData= (arr1, arr2, matchKey, filterKey, includeKey)=>{
arr1.forEach(o => {
const newObj ={};
const match = arr2.find(e => e[filterKey] === o[matchKey])
newObj[includeKey] = match ? match[includeKey] : null;
Object.assign(o, newObj);
});
}
mergeData(data, data2,'cat', 'pk', 'key3')
console.log(data)
Here is a solution that takes advantage of map and object spread to produce a new array with the desired key added into the target array's elements:
var jsonsToAddTo = [
{'cat':'k1','key2':'a'},
{'cat':'k1','key2':'b'},
{'cat':'k2','key2':'a'},
{'cat':'k2','key2':'b'},
{'cat':'k3','key2':'a'}
]
var additionalData = [
{'pk':'k1','key3':'data1'},
{'pk':'k2','key3':'data2'},
{'pk':'k3','key3':'data3'},
]
function denormalizeJsonOnKey(targetJsonArray,targetKeyToMatch, sourceJsonArray, sourceKeyToMatch, keyToAdd){
return targetJsonArray.map(thisJson => {
const addObj = sourceJsonArray.find(thatJson => thatJson[sourceKeyToMatch] === thisJson[targetKeyToMatch]);
return {
...thisJson,
...addObj ? {[keyToAdd]: addObj[keyToAdd]} : {},
}
});
}
console.log(denormalizeJsonOnKey(jsonsToAddTo, 'cat', additionalData, 'pk', 'key3'))
Note that this solution won't mutate the original array, so the jsonsToAddTo variable will be the same after you invoke the function. If you want to replace the original, you can always just re-assign it:
jsonsToAddTo = denormalizeJsonOnKey(jsonsToAddTo, 'cat', additionalData, 'pk', 'key3')
Try this,
using maps for both iteration,
var jsonsToAddTo = [{'cat':'k1','key2':'a'},{'cat':'k1','key2':'b'},
{'cat':'k2','key2':'a'},{'cat':'k2','key2':'b'},
{'cat':'k3','key2':'a'}]
var additionalData = [{'pk':'k1','key3':'data1'},{'pk':'k2','key3':'data2'},{'pk':'k3','key3':'data3'},
]
function denormalizeJsonOnKey(targetJsonArray,targetKeyToMatch, sourceJsonArray, sourceKeyToMatch, keyToAdd){
jsonsToAddTo.map((obj,index)=> {
additionalData.map((o,idx)=> {
if(obj[targetKeyToMatch]==o[sourceKeyToMatch]){
obj[keyToAdd]=o[keyToAdd];
}
})
})
return jsonsToAddTo
}
console.log(denormalizeJsonOnKey(jsonsToAddTo,'cat',additionalData,'pk','key3'))
var targetJsonArray = jsonsToAddTo.map(function(json, index) {
additionalData.forEach(function(data) {
if (data.pk === json.cat) {
json.key3 = data.key3;
}
})
return json;
})
Rather than nesting loops here, which will iterate the entire additionalData array for every entry in jsonsToAddTo, I suggest building an object map of the additionalData dataset once at the beginning, and then reference this within a .map on the target dataset:
var jsonsToAddTo = [
{'cat':'k1','key2':'a'},
{'cat':'k1','key2':'b'},
{'cat':'k2','key2':'a'},
{'cat':'k2','key2':'b'},
{'cat':'k3','key2':'a'}
]
var additionalData = [
{'pk':'k1','key3':'data1'},
{'pk':'k2','key3':'data2'},
{'pk':'k3','key3':'data3'},
]
// Adds a key value pair from sourceJson to targetJson based on a matching value
function denormalizeJsonOnKey(targetJsonArray,targetKeyToMatch, sourceJsonArray, sourceKeyToMatch, keyToAdd){
// Build an object of items keyed on sourceKeyToMatch
const sourceJsonMap = sourceJsonArray.reduce((obj, item) => (obj[item[sourceKeyToMatch]]=item, obj), {});
return targetJsonArray.map(item => {
const targetValue = item[targetKeyToMatch];
if (sourceJsonMap.hasOwnProperty(targetValue)) {
item[keyToAdd] = sourceJsonMap[targetValue][keyToAdd];
}
return item;
});
}
console.log(denormalizeJsonOnKey(jsonsToAddTo,'cat',additionalData,'pk','key3'))
Doing it this way should be far more efficient, especially if the dataset you are working on is fairly large.
I have the following code:
var fieldArr = [];
dimensions.forEach(function (dimension) {
fieldArr.push({dimension.id:dimension.name});
});
This generates an error.
What I'm trying to do is given this dimensions
{
id: abc
name: ddd
},
{
id: aaa
name:kkk
}
I want the fieldsArr to look like this
[abc] -> ddd
[aaa] -> kkk
You need to populate an object rather than an array.
Javascript
var dimensions = [{
id: "abc",
name: "ddd"
}, {
id: "aaa",
name: "kkk"
}],
fieldArr = {};
dimensions.forEach(function (dimension) {
fieldArr[dimension.id] = dimension.name;
});
console.log(fieldArr);
Output
Object {abc: "ddd", aaa: "kkk"}
jsfiddle
Then fieldArr shouldn't be an array, but an object.
var fieldArr = {};
dimensions.forEach(function (dimension) {
fieldArr[dimension.id] = dimension.name;
});
simply
fieldArr[dimension.id] = dimension.name