How to create object using pair values from another object in javascript - javascript

How to create object using pair values from another object in javascript
Input:
{
firstObject:{
{
"version":"1000",
"issue":"issue1"
},
{
"version":"1001",
"issue":"issue2"
},
{
"version":"1000",
"issue":"issue3"
}
}
}
Above is my input and I want output as following:
{
newObject:{
"1000":["issue1", "issue3"],
"1001":["issue2"]
}
}

Your Input is not a valid JSON. firstObject should be an array instead of object.
Demo
var obj = {
"firstObject": [{
"version": "1000",
"issue": "issue1"
},
{
"version": "1001",
"issue": "issue2"
},
{
"version": "1000",
"issue": "issue3"
}
]
};
var newObject = {};
obj.firstObject.map((item) => {
if( !newObject[ item.version ]){
newObject[item.version] = [];
}
newObject[item.version].push(item.issue);
});
console.log({ newObject });

You can try this
let input = {
firstObject:[
{
"version":"1000",
"issue":"issue1"
},
{
"version":"1001",
"issue":"issue2"
},
{
"version":"1000",
"issue":"issue3"
}
]
}
function createNewObject( input ){
let output= {};
input.firstObject.map(( item ) => {
if( !output[ item.version ]){
output[ item.version ] =[]
}
output[ item.version ].push( item.issue )
})
return({
newObject: output
})
}
console.log( createNewObject( input ))

Related

Check if array of objects contain certain key

I need to determine if a certain key exists in an array of objects.
Here is a sample array:
arrOfObj = [{
"mainKey1": {
"subKey1": {
"innerKey1": {
"innerMostKey1": {
"key1": "value"
}
}
}
}
}, {
"mainKey2": {
"key2": "value"
}
}, {
"mainKey3": {
"subKey3": {
"key3": "value"
}
}
}
]
I was trying to do this but I get the wrong output:
const objKeys = Object.keys(arrOfObj)
console.log('objKeys = ' + JSON.stringify(arrOfObj))
Output is the index numbers:
objKeys = ["0", "1", "2"]
I want to have a function that works like this:
var isKeyPresent = checkKeyPresenceInArray('mainKey3')
Please note though that I only need to check the topmost level in the objects - in above example, these are the main keys (mainKey1, etc) and that their content is dynamic (some others have deeply nested object inside and some not so.
Help!
You can try using array.some():
let checkKeyPresenceInArray = key => arrOfObj.some(obj => Object.keys(obj).includes(key));
let arrOfObj = [{
"mainKey1": {
"subKey1": {
"innerKey1": {
"innerMostKey1": {
"key1": "value"
}
}
}
}
}, {
"mainKey2": {
"key2": "value"
}
}, {
"mainKey3": {
"subKey3": {
"key3": "value"
}
}
}
]
let checkKeyPresenceInArray = key => arrOfObj.some(obj => Object.keys(obj).includes(key));
var isKeyPresent = checkKeyPresenceInArray('mainKey3')
console.log(isKeyPresent);
You can iterate through the array, check and see if any of the objects has the key that you are looking for, and return true if it does. If you don't find the key, then the for loop will complete and it will return false.
arrOfObj = [{
"mainKey1": {
"subKey1": {
"innerKey1": {
"innerMostKey1": {
"key1": "value"
}
}
}
}
}, {
"mainKey2": {
"key2": "value"
}
}, {
"mainKey3": {
"subKey3": {
"key3": "value"
}
}
}
]
function arrayHasKey(arr, key) {
for (const obj of arr) {
if (key in obj) { return true; }
}
return false;
}
console.log(arrayHasKey(arrOfObj, "mainKey2"))
console.log(arrayHasKey(arrOfObj, "mainKey10"))
this will work,it returns boolean value:
arrOfObj.hasOwnProperty('mainKey3');
You can use some with hasOwnProperty like this :
let checkKeyPresenceInArray = (key) => arrOfObj.some((o) => o.hasOwnProperty(key));
You have to use hasOwnProperty method to check if the key is available in the objects in that array -
var c = 0;
arrOfObj.forEach(e => {
if(e.hasOwnProperty("mainKey1")){
c++;
}
});
if(c > 0 && c == arrOfObj.length){
console.log("The key is found in all the objects in the array.");
}
else if(c == 0){
console.log("The key is not found in any objects in the array");
}
else{
console.log("The key is found in some objects in the array");
}
It is possibly to apply JSON.stringify() for that purpose:
let list = [{
"data1": {
"subKey1": {
"innerKey1": {
"innerMostKey1": {
"key1": "value"
}
}
}
}
}, {
"data2": {
"key2": "value"
}
}, {
"data3": {
"subKey3": {
"key3": "value"
}
}
}
]
let checkIfInArray = key => list.some(obj => JSON.stringify(obj).indexOf(key) > -1);
var result = checkIfInArray('key2')
alert(result);

how to add an element inside a json array at the specific index in a repeating block?

I am trying to add element "delete:true" after each occurrence of "_rev " mentioned in the below sample request.
Original Request:
{
"docs": [
{
"_id": "123",
"_rev": "1-7836",
},
{
"_id": "456",
"_rev": "1-1192",
}
]
}
Expected Request:
{
"docs": [
{
"_id": "123",
"_rev": "1-7836",
"_deleted" :true
},
{
"_id": "456",
"_rev": "1-1192",
"_deleted" :true
}
]
}
When I tried the below code,the ""_deleted" :true" is getting inserted after the -rev element is closed. PFB for the same and suggest.
function main(params) {
for (var i = 0; i< params.docs.length; i++) {
for (var value in params.docs[i]) {
if(value == '_rev' && params.docs[i]._rev ){
var string1 = JSON.stringify(params.docs[i]);
var str = ',';
var string2 = '"';
var string3 =str+string2+ '_deleted'+ string2+ ':' + "true" ;
var res = string1 + string3 ;
}
}
}
}
######################
[
"2018-01-23T09:44:23.568738362Z stdout:
{\"_id\":\"123\",
\"_rev\":\"1-7836\"},
\"_deleted\":true"]
Use map and Object.assign instead of generating a string
var output = params.docs.map( s => Object.assign( {}, {"_deleted" :true}, s ) );
You can then convert this to string using JSON.stringify( output );
Demo
var params = {
"docs": [{
"_id": "123",
"_rev": "1-7836",
},
{
"_id": "456",
"_rev": "1-1192",
}
]
};
var output = params.docs.map(s => Object.assign({}, {
"_deleted": true
}, s));
console.log(output);
var data = {
"docs": [
{
"_id": "123",
"_rev": "1-7836",
},
{
"_id": "456",
"_rev": "1-1192",
}
]
}
var newData = data['docs'].map(item => {
item._delete = true
return item
})
console.log(newData);
Why don't you simply put ._deleted attribute to doc, like this ?
function main(params) {
for (var i = 0; i< params.docs.length; i++) {
params.docs[i]._deleted = true;
var res = JSON.stringify(params.docs[i]);
}
}
}
Or like this :
function main(params) {
for (var i = 0; i< params.docs.length; i++) {
params.docs[i]["_deleted"] = true;
var res = JSON.stringify(params.docs[i]);
}
}
}
You can reference the not existing attribute directly and assign an value:
#!/usr/bin/js
var myJSON = { "docs": [ { "_id":"123", "_rev":"1-200" } ] }
console.log(myJSON);
myJSON.docs[0]["_deleted"]=true;
console.log(myJSON);
Output of example:
# js append.js
{ docs: [ { _id: '123', _rev: '1-200' } ] }
{ docs: [ { _id: '123', _rev: '1-200', _deleted: true } ] }
Read the more extensive example here: Add new attribute (element) to JSON object using JavaScript
So this might be a duplicate ...

javascript: Sourcing defaults for one json object from another - handling arrays in different sort order

I am receiving a json as parameter and I also have a template base json. I need to check that all objects of the template json should are present in the tgt json and if not, need to initialize those variables with template json.
Following is my implementation.
var jsonBase = {
"Et":"Val_Retain",
"A1": {
"A12": {
"A12Array": [
{
"key1": "val1"
},
{
"key2": "val2"
}
]
}
}
}
var jsonTgt = {
"Et":"OldVal",
"A1": {
"A12": {
"A12Array": [
{
"key1": "val1Old_Retain"
}
]
}
}
}
initKeys(jsonBase,jsonTgt)
function initKeys(obj,tgt) {
Object.keys(obj).forEach(function(element, key, _array) {
var cur;
if (typeof(tgt[element])=="undefined") {
tgt[element]=obj[element]
}
if (typeof(obj[element])=="object") {
initKeys(obj[element],tgt[element])
}
})
}
console.log(JSON.stringify(jsonTgt))
The output is:
{
"Et": "OldVal",
"A1": {
"A12": {
"A12Array": [{
"key1": "val1Old_Retain"
}, {
"key2": "val2"
}
]
}
}
}
There are two questions:
Is this correct approach or there could be a more efficient or a
simpler one with available js/nodejs libs?
More Importantly - What do I do in case if the array sort order doesn't match with template as below.
Changed sort order
var json2 = {
"Et":"OldVal",
"A1": {
"A12": {
"A12Array": [
{
"key2": "val1Old_Retain"
}
]
}
}
}
The above produces the following output:
{
"Et": "OldVal",
"A1": {
"A12": {
"A12Array": [{
"key2": "val1Old_Retain",
"key1": "val1"
}, {
"key2": "val2"
}
]
}
}
}
as against the desired:
{
"Et": "OldVal",
"A1": {
"A12": {
"A12Array": [{
"key1": "val1"
}, {
"key2": "val1Old_Retain"
}
]
}
}
}
Here is the first sample code I have been able to make and it works, however, I think that the way you implemented your code is wrong since I am pretty sure you could have done something much simpler if you had in mind functional programming methods i.e. those native methods from mdn, and those ones from lodash library don't forget to mark as answered if I did, otherwise please comment so I get more information about your exact situation
var _ = require('lodash')
let jsonInput = {
"Et": "Val_Retain",
"A1": {
"A12": {
"A12Array": [{
"key1": "val1"
}, {
"key2": "val2"
}]
}
}
}
let jsonInput2 = {
"Et": "OldVal",
"A1": {
"A12": {
"A12Array": [{
"key1": "val1Old_Retain"
}]
}
}
}
for (let key1 in jsonInput) {
if (key1 === 'Et') {
jsonInput[key1] = "OldVal"
} else {
for (let key2 in jsonInput[key1]) {
for (let key3 in jsonInput[key1][key2]) {
console.log(jsonInput[key1][key2][key3])
let listOfKeys = getKeys(jsonInput[key1][key2][key3])
console.log(listOfKeys)
console.log(jsonInput2[key1][key2])
console.log(key3)
let listOfKeys2 = getKeys(jsonInput2[key1][key2][key3])
console.log(listOfKeys2)
let uniqkeys = _.uniq(listOfKeys.concat(listOfKeys2))
let sortedUniqkeys = _.sortBy(uniqkeys)
let result = []
console.log('sortedUniqkeys', sortedUniqkeys)
sortedUniqkeys.forEach((key4, i) => {
let doc = {}
if (listOfKeys2.indexOf(key4) != -1) {
jsonInput2[key1][key2][key3].forEach((e, i) => {
if (e[key4]) {
doc[key4] = e[key4]
}
})
} else {
jsonInput[key1][key2][key3].forEach((e, i) => {
if (e[key4]) {
doc[key4] = e[key4]
}
})
}
result.push(doc)
console.log(key4, jsonInput[key1][key2][key3][key4])
console.log(result)
})
jsonInput[key1][key2][key3] = result
}
}
}
}
function getKeys(arr) {
console.log(arr)
return arr.reduce(function(accumulator, value, index, array) {
for (let key3 in value) {
accumulator.push(key3)
}
return accumulator
}, []);
}
console.log(JSON.stringify(jsonInput))

How can I remove the parent keys from a javascript Object?

I currently have this Object:
schoolsObject = [{
"college_1":
{
"id":"college_1",
"location":"Victoria",
"name":"College One"
},
"college_2":
{
"id":"college_2",
"location":"Tasmania",
"name":"College Two"
}
}];
I want to remove the top level keys ie. college_1, college_2 and 'flatten' the object out like this, so I have no 'top level' keys:
flatSchoolsObject =
[{
"id":"college_1",
"location":"Victoria",
"name":"College One"
},
{
"id":"college_2",
"location":"Tasmania",
"name":"College Two"
}];
Here is my latest attempt, I've made a lot of different try's but have not been documenting them:
// schoolIDs = Object.keys(schoolsObject);
var schools = {};
for(var i=0; i<Object.keys(schoolsObject).length; i++){
for (var property in schoolsObject) {
if (schoolsObject.hasOwnProperty(property)) {
schools[i] = {
'id': schoolsObject[property]['id'],
'name' : schoolsObject[property]['name'],
'location': schoolsObject[property]['location'],
};
}
}
}
console.log(schools)
Obviously this one is not what I'm after as it leaves me with Object {0: Object, 1: Object}.
Is what I want to do here possible or am I looking at it the wrong way?
Given Object:
schoolsObject = [{
"college_1":{
"id":"college_1",
"location":"Victoria",
"name":"College One"
},
"college_2":{
"id":"college_2",
"location":"Tasmania",
"name":"College Two"
}
}];
Solution:
Object.values(schoolsObject[0]);
Result:
[{
"id":"college_1",
"location":"Victoria",
"name":"College One"
},{
"id":"college_2",
"location":"Tasmania",
"name":"College Two"
}]
(Codewise) simplest solution could be using a combination of Object.keys() and Array.map():
flatSchoolsObject = Object.keys( schoolsObject[0] )
.map( ( key ) => schoolsObject[0][ key ] );
If the schoolsObject array has more entries, the code would have to be slightly adjusted:
let step1 = schoolsObject.map( ( el ) => {
return Object.keys( schoolsObject[0] )
.map( ( key ) => schoolsObject[0][ key ] );
})
flatSchoolsObject = [].concat.apply( [], step1 );
(the step1 variable is just introduced for readability reasons.)
You need to concat the result of extracting values from each item in schoolObject
flatSchoolsObject = [].concat.call(
schoolsObject.map(function(item) {
return Object.keys(item).map(function(key) {
return item[key];
})
})
)
or using Array.prototype.reduce
flatSchoolsObject = schoolsObject.reduce(function(acc, item) {
return acc.concat(Object.keys(item).map(function(key){
return item[key]
})
}, [])
You can use Array#map on the result of Object.keys to do it. Since you have just a single object in the array, we do it like this:
schoolsObject = Object.keys(schoolsObject[0]).map(function(key) {
return schoolsObject[0][key];
});
Live example:
var schoolsObject = [
{
"college_1": {
"id": "college_1",
"location": "Victoria",
"name": "College One"
},
"college_2": {
"id": "college_2",
"location": "Tasmania",
"name": "College Two"
}
}];
schoolsObject = Object.keys(schoolsObject[0]).map(function(key) {
return schoolsObject[0][key];
});
console.log(schoolsObject);
With ES2015+ you could use an arrow function to make that shorter:
schoolsObject = Object.keys(schoolsObject[0]).map(key => schoolsObject[0][key]);
// Code goes here
var schoolsObject = [{
"college_1":
{
"id":"college_1",
"location":"Victoria",
"name":"College One"
},
"college_2":
{
"id":"college_2",
"location":"Tasmania",
"name":"College Two"
}
}];
var result = Object.keys(schoolsObject[0]).map(function(key){
return schoolsObject[0][key];
})
console.log(result);
other version
var schoolsObject = [{
"college_1": {
"id": "college_1",
"location": "Victoria",
"name": "College One"
},
"college_2": {
"id": "college_2",
"location": "Tasmania",
"name": "College Two"
}
}];
var result = [];
for (var property in schoolsObject[0]) {
if (schoolsObject[0].hasOwnProperty(property)) {
result.push(schoolsObject[0][property]);
}
}
console.log(result);

Replace in array objects with same id using lodash

I am new with loash and need help on this.
i have 2 objects:
{
"data": [
{
"RHID": "2",
"NOME": "Leonor",
},
{
"RHID": "3",
"NOME": "José",
}
]
}
and
{
"data": [
{
"RHID": "2",
"NOME": "Leonor maria",
},
{
"RHID": "3",
"NOME": "José Leo",
}
]
}
How can i replace inner objects with same RHID if they are diferent. Keep the second.
I remove duplicates with
Form.myData[Form.arrData] = _.map(
_.uniq(
_.map(Form.myData[Form.arrData], function (obj) {
return JSON.stringify(obj);
})
), function (obj) {
return JSON.parse(obj);
}
);
i want to replace if diferent.
Thanks a lot .
solved with merge the oposite way
$.merge( newData[Form.arrData],Form.myData[Form.arrData]);
instead of
$.merge( Form.myData[Form.arrData],newData[Form.arrData]);
and then
Form.myData[Form.arrData] = _.map(
_.uniq(
_.map( newData[Form.arrData], function (obj) {
return JSON.stringify(obj);
})
), function (obj) {
return JSON.parse(obj);
}
);
instead of
Form.myData[Form.arrData] = _.map(
_.uniq(
_.map(Form.myData[Form.arrData], function (obj) {
return JSON.stringify(obj);
})
), function (obj) {
return JSON.parse(obj);
}
);

Categories