how do i rename key using javascript - javascript

let jsonObj = {
"compCode": "0001",
"vndrId": "0000000047",
"vndrName": "NKJFKFJFJKJJ",
"vndrName1": "jdkfjfkfjk",
"shortName": "fjkfjkfjkf",
"vndrStatus": "A",
"vndrType": "R",
"docStatus": "O",
"createdOn": "1970-01-01T00:00:00.000+0000",
"modifiedOn": "2017-10-11T10:33:35.000+0000",
"lastUser": "ashok",
"vndrAddr": [{
"addrId": "1",
"addr1": "jhghjbg",
"addr2": "jgbfhhj",
"addr3": "hjvfddfh",
"city": "DJHHVH",
"state": "JH",
"pinCode": "855485",
"effDate": "1970-01-01T00:00:00.000+0000",
"effStatus": "A",
"vndrContact": [{
"contId": "1",
"contName": "gnghh",
"contDesg": "ghhgh",
"contPh": "5625458",
"contEmail": "gfhj#bjhg.com"
}, {
"contId": "1",
"contName": "gnh",
"contDesg": "ghgh",
"contPh": "562558",
"contEmail": "ghj#bjhg.com"
}
]
}, {
"addrId": "2",
"addr1": "jhghjbg",
"addr2": "jgbfhhj",
"addr3": "hjvfddfh",
"city": "DJHHVH",
"state": "JH",
"pinCode": "855485",
"effDate": "1970-01-01T00:00:00.000+0000",
"effStatus": "A",
"vndrContact": [{
"contId": "3",
"contName": "nghh",
"contDesg": "hhgh",
"contPh": "562558",
"contEmail": "gfj#bhg.com"
}, {
"contId": "4",
"contName": "gngh",
"contDesg": "ghhh",
"contPh": "56458",
"contEmail": "gfh#bjh.com"
}]
}],
"vndrRegn": [{
"regnId": 1,
"regnType": "V",
"regnNo": "ABCDEFGHJ",
"regnDate": "2016-10-01T00:00:00.000+0000",
"regnAuth": "jfkjfjfjf",
"regnExpiry": "2022-10-01T00:00:00.000+0000",
"effDate": "2016-10-01T00:00:00.000+0000",
"effStatus": "A"
}, {
"regnId": 2,
"regnType": "S",
"regnNo": "ABCDEFGHJ",
"regnDate": "2016-10-01T00:00:00.000+0000",
"regnAuth": "jfkjfjfjf",
"regnExpiry": "2022-10-01T00:00:00.000+0000",
"effDate": "2016-10-01T00:00:00.000+0000",
"effStatus": "A"
}]
}
My object look like this. How do I rename each key inside an array or object and create a key value array using javascript ?
My result should look like this
compCode:0001
vndrId:00088
vndrName:JXCHXDDJKCJ
vndrName1:JFVHSSSJFDH
shortName:jvgshqxz
vndrStatus:A
vndrType:R
docStatus:O
createdOn:18-10-2017 11:32:28
modifiedOn:23-10-2017 18:51:58
lastUser:ashok
vndrAddr[0].addrId:1
vndrAddr[0].addr1:vfdfvf
vndrAddr[0].addr2:nbnsdvd
vndrAddr[0].addr3:bdfb
vndrAddr[0].city:vbvfb
vndrAddr[0].state:JH
vndrAddr[0].pinCode:3332
vndrAddr[0].effDate:02-10-2012
vndrAddr[0].effStatus:A
vndrAddr[0].vndrContact[0].contId:1
vndrAddr[0].vndrContact[0].contName:jvffvjh
vndrAddr[0].vndrContact[0].contDesg:hvhjjvf
vndrAddr[0].vndrContact[0].contPh:vjhhjv
vndrAddr[0].vndrContact[0].contEmail:fhhf#fj.com
vndrAddr[1].addrId:2
vndrAddr[1].addr1:hjdfhjfhj
vndrAddr[1].addr2:vffvhjh
vndrAddr[1].addr3:hfvfhj
vndrAddr[1].city:hjvhjdf
vndrAddr[1].state:JH
vndrAddr[1].pinCode:255
vndrAddr[1].effDate:02-12-2012
vndrAddr[1].effStatus:A
vndrAddr[1].vndrContact[0].contId:1
vndrAddr[1].vndrContact[0].contName:dfvhjf
vndrAddr[1].vndrContact[0].contDesg:fvjhfvhj
vndrAddr[1].vndrContact[0].contPh:fvhjjhfv
vndrAddr[1].vndrContact[0].contEmail:hdhd#hf.com

You could take an iterative and recursive approach by saving the type for array indices with brackets. Later assign the value the the new property of the path.
function setPath(object) {
function iter(object, path, isArray) {
Object.keys(object).forEach(function (key) {
var temp = path + (isArray ? '[' + key + ']' : (path && '.') + key);
if (object[key] && typeof object[key] === 'object') {
return iter(object[key], temp, Array.isArray(object[key]));
}
result[temp] = object[key];
});
}
var result = {};
iter(object, '');
return result;
}
var object = { a: { b: [{ c: { d: 'foo' } }, 'bar'] } };
console.log(setPath(object));

Related

Group array of objects with a specific key value pushed first

Given the following Array of Objects:
[
{
"teamFK": 8650,
"code": "yellow_cards",
"typeId": 554,
"value": "5",
"side": "home"
},
{
"teamFK": 8650,
"code": "goals",
"typeId": 554,
"value": "1",
"side": "home"
},
{
"teamFK": 8990,
"code": "yellow_cards",
"typeId": 555,
"value": "2",
"side": "away"
},
{
"teamFK": 8990,
"code": "goals",
"typeId": 555,
"value": "0",
"side": "away"
}
]
I would like to group this data by code and get this result:
{
"stats": [
{
"name": "yellow_cards",
"stats": ["5","2"]
},
{
"name": "goals",
"stats": ["2","0"]
}
]
}
What I've done is the following which works but I want to make sure that the alway the stat with "side":"home" always pushed first into the array "stats": []:
const groupedStats = Object.entries(
query.reduce((acc, { typeId, value, code, side }) => {
if (!acc[code]) {
acc[code] = [];
}
acc[code].push(value);
return acc;
}, {}),
).map(([name, stats]) => ({ name, stats }));
My approach is sort it first by side using Array.sort() and then looping through the objects and adding it to stats
i created a const match to find if there is a match already so i dont have to add the name and value again basically if its not a match i'll add it to the stats array and if its a match then i'll just update the current index
const objs = [
{
teamFK: 8650,
code: "yellow_cards",
typeId: 554,
value: "5",
side: "home",
},
{
teamFK: 8650,
code: "goals",
typeId: 554,
value: "1",
side: "away",
},
{
teamFK: 8990,
code: "yellow_cards",
typeId: 555,
value: "2",
side: "away",
},
{
teamFK: 8990,
code: "goals",
typeId: 555,
value: "0",
side: "home",
},
];
let stats = [];
const transformedObj = objs
.sort((a, b) => {
if (a.side > b.side) {
return -1;
}
if (a.side < b.side) {
return 1;
}
return 0;
})
.forEach((obj) => {
const match = stats.find((stat) => stat.name === obj.code);
const statsIndex = stats.findIndex((stat) => stat.name === obj.code);
if (!match) {
stats = [...stats, { name: obj.code, value: [obj.value] }];
} else {
stats[statsIndex] = {
name: stats[statsIndex].name,
value: [...stats[statsIndex].value, obj.value],
};
}
});
console.log(stats);
You can sort array and use key grouping approach:
const data = [{"teamFK": 8650,"code": "yellow_cards","typeId": 554,"value": "5","side": "home"},{"teamFK": 8650,"code": "goals","typeId": 554,"value": "1","side": "home"},{"teamFK": 8990,"code": "yellow_cards","typeId": 555,"value": "2","side": "away"},{"teamFK": 8990,"code": "goals","typeId": 555,"value": "0","side": "away"}];
const groups = data
.sort(({ side: a }, { side: b }) => b.localeCompare(a))
.reduce((acc, { code, value }) => {
acc[code] ??= { name: code, stats: [] };
acc[code]['stats'].push(value);
return acc;
}, {});
const result = { stats: Object.values(groups) };
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }

How to remove complete unique value from array [duplicate]

This question already has answers here:
How to remove all duplicates from an array of objects?
(77 answers)
Closed 3 years ago.
How to remove complete record of same object in array please help me this, I am using below funtion but its only remove one value I want remove complete object of same object
var data = [{
"QuestionOid": 1,
"name": "hello",
"label": "world"
}, {
"QuestionOid": 2,
"name": "abc",
"label": "xyz"
}, {
"QuestionOid": 1,
"name": "hello",
"label": "world"
}];
function removeDumplicateValue(myArray) {
var newArray = [];
$.each(myArray, function (key, value) {
var exists = false;
$.each(newArray, function (k, val2) {
if (value.QuestionOid == val2.QuestionOid) { exists = true };
});
if (exists == false && value.QuestionOid != undefined) { newArray.push(value); }
});
return newArray;
}
I want result like this
[{
"QuestionOid": 2,
"name": "abc",
"label": "xyz"
}]
You can use reduce.
var data = [{"QuestionOid": 1,"name": "hello","label": "world"}, {"QuestionOid": 2,"name": "abc","label": "xyz"}, {"QuestionOid": 1,"name": "hello","label": "world"}];
let op = data.reduce((op,inp)=>{
if(op[inp.QuestionOid]){
op[inp.QuestionOid].count++
} else {
op[inp.QuestionOid] = {...inp,count:1}
}
return op
},{})
let final = Object.values(op).reduce((op,{count,...rest})=>{
if(count === 1){
op.push(rest)
}
return op
},[])
console.log(final)
Do with Array#filter.Filter the array matching QuestionOid value equal to 1
var data = [{ "QuestionOid": 1, "name": "hello", "label": "world" }, { "QuestionOid": 2, "name": "abc", "label": "xyz" }, { "QuestionOid": 1, "name": "hello", "label": "world" }]
var res = data.filter((a, b, c) => c.map(i => i.QuestionOid).filter(i => i == a.QuestionOid).length == 1)
console.log(res)

Single variable to stand in for multiple key names - javascript

I have an array, something like this:
array =
[
{
"type": "apple",
"color": "red",
"id": "redApple"
},
{
"type": "grape",
"color": "green",
"id": "greenGrape",
"options": [
{
"bunchName": "bunch1",
"size": "8"
},
{
"bunchName": "bunch2",
"size": "10"
},
{
"bunchName": "bunch3",
"size": "5"
}
]
}
]
I have a function that searches for values in the array.
function findValue (index, key) {
return array[index][key];
}
var value = findValue(0, "id");
// returns redApple
Is there a way I could pass a single argument to the function if I wanted to find something deeper in the array? For example, if I wanted to find "bunchName" could I pass it something like 1, "options[0].bunchName" and get back "bunch1"?
I want a function that can handle multiple keys. In my real project sometimes I'm looking for something on the first level, sometimes I'm looking on the second level, sometimes the third level, etc.
jQuery can be used if for some reason that would help.
You could take the string, replace the brackets, split the string and reduce the path for the result. The function uses a default object for missing or not given properties.
function getValue(object, path) {
return path
.replace(/\[/g, '.')
.replace(/\]/g, '')
.split('.')
.reduce(function (o, k) { return (o || {})[k]; }, object);
}
function findValue(index, path) {
return getValue(array[index], path);
}
var array = [{ type: "apple", color: "red", id: "redApple" }, { type: "grape", color: "green", id: "greenGrape", options: [{ bunchName: "bunch1", size: "8" }, { bunchName: "bunch2", size: "10" }, { bunchName: "bunch3", size: "5" }] }];
console.log(findValue(1, "options[0].bunchName"));
From what I understand, output of findValue(object, "bunchName"); should be "bunch3", where object is array in OP's example.
var object =
[
{
"type": "apple",
"color": "red",
"id": "redApple"
},
{
"type": "grape",
"color": "green",
"id": "greenGrape",
"options": [
{
"bunchName": "bunch1",
"size": "8"
},
{
"bunchName": "bunch2",
"size": "10"
},
{
"bunchName": "bunch3",
"size": "5"
}
]
}
]
var findValue = (object, key) => {
var resultValue;
var rec = (currentObj) => {
if(currentObj && typeof currentObj === "object"){
for(let curKey in currentObj){
if (curKey === key){
resultValue = currentObj[curKey];
}else{
rec(currentObj[curKey]);
}
}
}
}
rec(object);
return resultValue;
}
console.log(findValue(object, "bunchName"));
You could add a function that takes an object and a key and returns object[key] and then split your key string into a list of individual keys by the dot. Then you could traverse the list of keys and use the function to get the value for each level in your object:
Totally untested code I just whipped up:
function valueByKey(obj, key) {
if (obj) {
return obj[key];
}
}
function findValue(index, key) {
const keys = key.split('.');
let value = array[index];
for (let i = 0; i < keys.length; i++) {
value = valueByKey(value, keys[i]);
}
return value;
}
Non-recurrent solution:
var array = [
{
'a': {
'b': 1
}
}
];
function findValue(index, key) {
var keys = key.split('.');
var tmp = array[index];
for (var i = 0; i < keys.length; i++) {
if (!tmp.hasOwnProperty(keys[i]) || typeof tmp !== 'object') {
// throw an exception, or return default value – property not found.
}
tmp = tmp[keys[i]];
}
return tmp;
}
findValue(0, 'a.b');

How the outer array knows the inner array completed its iteration

In Javascript how the outer array knows the inner array completed its iteration? as I am iterating the below array with recursive function want to know how the outer function or outer array knows the inner array completed the iteration.
{
"rules": [
{
"id": 1,
"value": "ABC"
},
{
"id": 2,
"value": "PQR"
},
{
"id": 3,
"value": "XYZ"
},
{
"rules": [
{
"id": 10,
"value": "ST"
},
{
"id": 12,
"value": "UI"
}
]
},
{
"id": 5,
"value": "5XYZ"
}
]
}
Using the recursive function to iterate the array.
Require the output like
ABC,PQR,XYZ,5XYZ
Within Group ST,UI
Edit1
var message = '';
var infoMessage = getMessageData(false);
function getMessageData(isGroup) {
angular.forEach(rulesArray, function(v, k) {
if (rulesArray.id === undefined) {
message + = getMessageData(true);
} else {
message + = v.value;
if (isGroup) {
message + = 'Within Group' + v.value;
}
}
};
}
}
If I understand correct, you can try something like this:
Idea
Sort array based on objects that have rules and push them back
Loop over array and check
If object has id, concat value to response
If object has rules, use recursion and get response and concat it.
var data = { "rules": [{ "id": 1, "value": "ABC" }, { "id": 2, "value": "PQR" }, { "id": 3, "value": "XYZ" }, { "rules": [{ "id": 10, "value": "ST" }, { "id": 12, "value": "UI" } ] }, { "id": 5, "value": "5XYZ" } ] }
const key = 'rules';
data.rules.sort(function(a,b){
return +(key in a) - +(key in b);
});
function getMessage(obj) {
return obj.reduce(function (p, c, i, a){
if('id' in c) {
p += c.value + (i !== a.length -1 ? ', ': '');
}
if('rules' in c) {
p += getMessage(c.rules);
}
return p;
}, '')
}
console.log(getMessage(data.rules))
You you take a queue for collecting and processing all items of rules with a counter for inserting the group phrase.
function iterate(array) {
var queue = array.slice(),
group = array.length,
temp,
result = '';
while (queue.length) {
temp = queue.shift();
if (temp.rules) {
Array.prototype.push.apply(queue, temp.rules);
continue;
}
if (--group) {
result += (result && ', ') + temp.value;
continue;
}
result += ' Within Group ' + temp.value;
}
return result;
}
var data = { rules: [{ id: 1, value: "ABC" }, { id: 2, value: "PQR" }, { id: 3, value: "XYZ" }, { rules: [{ id: 10, value: "ST" }, { id: 12, value: "UI" }] }, { id: 5, value: "5XYZ" }] };
console.log(iterate(data.rules));

Push object keys and its values to array

I have an object like this:
{
"id": 23,
"name": "Jacob",
"link": {
"rel": "self",
"link": "www.abc.com"
},
"company":{
"data":{
"id": 1,
"ref": 324
}
}
I want to store each key with its value to an array in javascript or typescript like this
[["id":23], ["name":"Jacob"], ["link":{......, ......}]] and so on
I am doing this so that I can append an ID for each.
My best guess I would loop through the array and append an ID/a flag for each element, which I don't know how to do as well.... how to address this issue ? thanks
var arr = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
var innerObj = {};
innerObj[prop] = obj[prop];
arr.push(innerObj)
}
}
console.log(arr);
here is demo https://plnkr.co/edit/9PxisCVrhxlurHJYyeIB?p=preview
p.forEach( function (country) {
country.forEach( function (entry) {
entry.push( {"value" : 'Greece', "synonyms" : 'GR'});
});
});
you can try to use experimental Object.entries:
let obj = {
"id": 23,
"name": "Jacob",
"link": {
"rel": "self",
"link": "www.abc.com"
},
"company":{
"data":{
"id": 1,
"ref": 324
}
}};
console.log(Object.entries(obj).map(item => ({[item[0]]:item[1]})));
for unsupported browsers you can use polyfill: https://github.com/es-shims/Object.entries
You could use an iterative/recursive approach with the object and their nested parts. It works for any depths.
function getKeyValue(object) {
return Object.keys(object).reduce(function (result, key) {
return result.concat(
object[key] && typeof object[key] === 'object' ?
getKeyValue(object[key]) :
[[key, object[key]]]
);
}, []);
}
var data = { id: 23, name: "Jacob", link: { rel: "self", link: "www.abc.com" }, company: { data: { id: 1, ref: 324 } } };
console.log(getKeyValue(data));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use the Object.keys method to get an array of the keys, then use the Array#map method to return a new array containing individual objects for each property.
This ES6 one-liner should do it:
const splitObject = o => Object.keys(o).map(e => ({ [e]: o[e] }));
Or in ES5:
function splitObject(o) {
return Object.keys(o).map(function(e) {
return Object.defineProperty({}, e, {
value: o[e],
enumerable: true
});
});
}
var res = [];
_.transform( {
"id": 23,
"name": "Jacob",
"link": {
"rel": "self",
"link": "www.abc.com"
},
"company": {
"data": {
"id": 1,
"ref": 324
}
}
}, function(result, value, key) {
res.push(key +':'+value);
}, {});
You can use underscore
Supported in all major browser, including IE11
Object.entries() gives you exactly this.
const obj = {
id: 23,
name: 'Jacob',
link: {
rel: 'self',
link: 'www.abc.com'
},
company: {
data: {
id: 1,
ref: 324
}
}
};
Object.entries(obj);
// output:
[
[
"id",
23
],
[
"name",
"Jacob"
],
[
"link",
{
"rel": "self",
"link": "www.abc.com"
}
],
[
"company",
{
"data": {
"id": 1,
"ref": 324
}
}
]
]
var obj=[{"Name":ABC,"Count":123},{"Name":XYZ,"Count":456}];
var arr = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
var innerObj = {};
innerObj[0] = obj[prop];
arr.push(innerObj[0]);
}
}
/* Here above exmple innerobj index set to 0 then we will get same data into arr if u not menstion then arr will conatins arr[0] our result.
then we need to call first record obj arr[0][0] like this*/
const foo = { "bar": "foobar", "foo": "foobar" }
Object.entries(foo)
should result in:
[["bar", "foobar"], ["foo", "foobar"]]
maybe there's a function to pass to convert all commas to colons
Here's the documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

Categories