Split object keys with same prefix to new objects - javascript

For example, given an object with keys and values
{
prefix_1_a: 1a,
prefix_1_b: 1b,
prefix_2_a: 2a,
prefix_2_b: 2b,
}
I want convert into two objects:
prefix_1 with keys and values {a: 1a, b: 1b}
prefix_2 with keys and values {a: 2a, b: 2b}
another example ,given a formData object:
["item_0_orange":"10",
"item_0_apple:"20",
"item_0_grape":"30",
"item_1_orange":"40",
"item_1_apple":"50",
"item_1_grape":"60",
"item_2_orange":"40",
"item_2_apple":"50",
"item_2_grape":"60"]
and I want to convert to json object
fruitprice:
[
{key:0 ,orange:"10" , apple:"20" , grape:"30" },
{key:1 ,orange:"40" , apple:"50" , grape:"60" },
{key:2 ,orange:"40" , apple:"50" , grape:"60" }
]
how to search and add key and value under a position when match same prefix
here is my code:
var fruitObject ={};
for(i=0;i<3;i++)
{
var prefix = "item_" + i;
var res = key.split("_");
var newKey = res[2];
if(key.startsWith(prefix))
{
var newObject = {};
newObject[newKey] =value;
addObject(res[1],newObject, fruitObject); //by given key
return;
};
}

It can be a costly transformation, but not that complex:
Let's start with the input:
const data = {
"item_0_orange": "10",
"item_0_apple": "20",
"item_0_grape": "30",
"item_1_orange": "40",
"item_1_apple": "50",
"item_1_grape": "60",
"item_2_orange": "40",
"item_2_apple": "50",
"item_2_grape": "60",
}
Then have a look at the desired output:
const fruitprices = [
{
key: 0,
orange: "10",
apple: "20",
grape: "30"
},
{
key: 1,
orange: "40",
apple: "50",
grape: "60",
},
{
key: 2,
orange: "40",
apple: "50",
grape: "60",
}
]
And here's a transformation from data to fruitprices:
// this is an Object, not an Array!
const data = {
"item_0_orange": "10",
"item_0_apple": "20",
"item_0_grape": "30",
"item_1_orange": "40",
"item_1_apple": "50",
"item_1_grape": "60",
"item_2_orange": "40",
"item_2_apple": "50",
"item_2_grape": "60",
}
// transform function
const fruitprices = Object.entries(data).reduce((a, [key, val]) => {
// destructuring the key; "prefix" is not going to be used
const [prefix, outkey, fruit] = key.split('_')
// trying to find the item in the "a" Array
const item = a.find(({
key: itemkey
}) => itemkey === outkey)
if (item) { // if the key is already in the "a" Array
item[fruit] = val
} else { // if the key is not in the "a" Array yet
a.push({
key: outkey,
[fruit]: val
})
}
return a
}, [])
console.log(fruitprices)

Related

convert object into array and scroll it all value

How do I convert an object to an array and each scroll it all?
this is my object
let obj = {
each_hour: "20000",
edit_photo: { yes: "20000", no: "0" },
photo_type: { Personal: "1000", sport: "2100", Industrial: "1200", Commercial: "2300", Fashion: "1300", mode: { "name": "farhad" } },
photograph_gender: { male: "0", female: "20000" }
}
Required output:
each_hour
20000
edit_photo
yes
20000
no
0
photo_type
Personal
1000
sport
2100
Industrial
1200
...
As the data stands currently in the object, you can try using JSON.stringify(), replace() and split() like the following way:
let obj = {
each_hour: "20000",
edit_photo: { yes: "20000", no: "0" },
photo_type: { Personal: "1000", sport: "2100", Industrial: "1200", Commercial: "2300", Fashion: "1300", mode: { "name": "farhad" } },
photograph_gender: { male: "0", female: "20000" }
}
var res = JSON.stringify(obj).replace(/["{}]/g,'').split(/[:,]/);
console.log(res);
You can use a recursive function to loop through your object. If an array is passed into your function, you can map each value in the array to the return value of calling your function again on that individual element. If an object is passed through, you can obtain its entries by calling Object.entries() on your object, which will then execute the previously mentioned array mapping. Otherwise, if it's not an array or an object, you can return the value:
function traverseObject(val) {
if(Array.isArray(val)) {
return val.flatMap(elem => traverseObject(elem));
} else if(Object(val) === val) {
return traverseObject(Object.entries(val));
}
return val;
}
const obj = { each_hour: "20000", edit_photo: { yes: "20000", no: "0" }, photo_type: { Personal: "1000", sport: "2100", Industrial: "1200", Commercial: "2300", Fashion: "1300", mode: { "name": "farhad" } }, photograph_gender: { male: "0", female: "20000" } }
traverseObject(obj).forEach(e => console.log(e));
You could also use the replacer function of JSON.stringify, as that will be called on every key/value pair in your object, but it's a little bit of a hack:
function traverseObject(obj) {
const res = [];
JSON.stringify(obj, (key, val) => (key !== "" && res.push(key, ...(Object(val) === val ? [] : [val])), val));
return res;
}
// works with arrays -\/
const obj = { foo: [4, 5, 6], each_hour: "20000", edit_photo: { yes: "20000", no: "0" }, photo_type: { Personal: "1000", sport: "2100", Industrial: "1200", Commercial: "2300", Fashion: "1300", mode: { "name": "farhad" } }, photograph_gender: { male: "0", female: "20000" } }
traverseObject(obj).forEach(e => console.log(e));
More old school (imperative coding style) approach with recursion if interested :-
Basically maintaining an output array to which we push the key and value obtained from Object.entries. If the value is an object, we recurse and if not we simply push to our output array.
Note - This is specific to your use case and not very generalized.
let obj = {
each_hour: "20000",
edit_photo: { yes: "20000", no: "0" },
photo_type: { Personal: "1000", sport: "2100", Industrial: "1200", Commercial: "2300", Fashion: "1300", mode: { "name": "farhad" } },
photograph_gender: { male: "0", female: "20000" }
}
function objToArray(obj){
const output = [];
function processing(obj){
for (const [key,value] of Object.entries(obj)){
if(typeof value === 'object' ){
output.push(key);
processing(value);
}
else{
output.push(key,value);
}
}
}
processing(obj);
return output;
}
const result = objToArray(obj);
console.log(result);

JSON array of object Convert

Here is my data array
let data = [{
"name": "s1",
"age": 20,
"address": "abc"
}, {
"name": "s2",
"age": 21,
"address": "def"
}];
i want to convert my data array into my filter array.
let filters = [
{
"field": "name",
"values": [{
"label": "s1",
"value": "s1"
}, {
"label": "s2",
"value": "s2"
}]
},
{
"field": "age",
"values": [{
"label": "21",
"value": "21"
}, {
"label": "20",
"value": "20"
}]
},
{
"field": "address",
"values": [{
"label": "abc",
"value": "abc"
}, {
"label": "def",
"value": "def"
}]
}
];
You could take a Map for collecting same field and their values. Then get the objects with the wanted items.
const
getValue = v => ({ label: v, value: v });
let data = [{ name: "s1", age: 20, address: "abc" }, { name: "s2", age: 21, address: "def" }],
filters = Array.from(
data.reduce((m, o) =>
Object
.entries(o)
.reduce((n, [k, v]) => n.set(k, [...(n.get(k) || []), getValue(v)]), m), new Map),
([field, values]) => ({ field, values })
);
console.log(filters);
.as-console-wrapper { max-height: 100% !important; top: 0; }
you'll need to extract the Object.keys of the first element or all of the elements if they may have different keys, then map throught the result to add the structure you want :
let data = [{
"name": "s1",
"age": 20,
"address": "abc"
}, {
"name": "s2",
"age": 21,
"address": "def"
}];
let fields = [...new Set(data.map(e => Object.keys(e)).flat())]; // extract the keys
// Or
/*
let fields = Object.keys(data[0]); // if you're sure that all the array entries have the same fields.
*/
let filters = fields.map(field => ({
field,
values: data.map(e => ({
label: e[field],
value: e[field]
}))
}))
console.log(filters)
First,define three Java DTOs,like this:
public class Data {
private String name;
private String age;
private String address;
// getter setter
}
public class Value {
private String label;
private String value;
}
public class Response {
private String field;
private List<Value> values;
}
Second,the main code:
public static void main(String[] args) throws Exception {
File file = new File("inputFileName");
TypeReference<List<Data>> reference = new TypeReference<List<Data>>() {
};
ObjectMapper mapper = new ObjectMapper();
List<Data> datas = mapper.readValue(file,reference);
JSONArray object = JSONArray.fromObject(datas);
Iterator iterator = object.iterator();
Map<String,List<Value>> var0 = new HashMap<>();
while (iterator.hasNext()) {
JSONObject jsonObject = (JSONObject) iterator.next();
Set<String> keys = jsonObject.keySet();
for(String key : keys) {
List<Value> values = var0.get(key);
if (null == values) {
values = new ArrayList<>();
values.add(new Value(jsonObject.getString(key),jsonObject.getString(key)));
var0.put(key,values);
} else {
values.add(new Value(jsonObject.getString(key),jsonObject.getString(key)));
}
}
}
List<Response> responses = new ArrayList<>(var0.size());
for(Map.Entry<String,List<Value>>entry:var0.entrySet()) {
Response response = new Response();
response.setField(entry.getKey());
response.setValues(entry.getValue());
responses.add(response);
}
File outPutFile = new File("outputFileName");
mapper.writeValue(outPutFile,responses);
}

Create grouped object out of array of Strings in JavaScript

I have an issue I've not been able to solve, basically I want to transform this:
{
"seamark:name": "Z-2",
"seamark:type": "buoy_lateral",
"seamark:light:range": "5",
"seamark:light:colour": "red",
"seamark:light:character": "Q",
"seamark:radar_reflector": "yes",
"seamark:buoy_lateral:shape": "can",
"seamark:buoy_lateral:colour": "red",
"seamark:buoy_lateral:system": "iala-a",
"seamark:buoy_lateral:category": "port"
}
into this:
{
seamark: {
name: "Z-2",
type: "buoy_lateral",
light: {
range: "5",
colour: "red",
reflector: "yes"
},
buoy_lateral: {
shape: "can",
colour: "red",
system: "iala-a",
category: "port
}
}
}
For now I've only achieved to get an array containing 10 objects with every time the path to the value (for example {seamark: {name: "Z-2"}}) using the code shown in the following link:
codepen
Would anyone have an idea on how to group the properties deeply once I have the result shown in the codepen? Or maybe even another idea? thanks in advance
You are trying to unflat an object.
You can use flat npm (https://www.npmjs.com/package/flat)
const { unflatten } = require('flat');
const unflat = unflatten({
"seamark:name": "Z-2",
"seamark:type": "buoy_lateral",
"seamark:light:range": "5",
"seamark:light:colour": "red",
"seamark:light:character": "Q",
"seamark:radar_reflector": "yes",
"seamark:buoy_lateral:shape": "can",
"seamark:buoy_lateral:colour": "red",
"seamark:buoy_lateral:system": "iala-a",
"seamark:buoy_lateral:category": "port"
}, { delimiter: ":" }); // notice delimiter : default is "."
console.log(unflat);
Output:
{
seamark: {
name: 'Z-2',
type: 'buoy_lateral',
light: { range: '5', colour: 'red', character: 'Q' },
radar_reflector: 'yes',
buoy_lateral:
{
shape: 'can',
colour: 'red',
system: 'iala-a',
category: 'port'
}
}
}
For setting a value, you could split the path and reduce the path by walking the given object. If no object exist, create a new property with the name. Later assign the value.
function setValue(object, path, value) {
var last = path.pop();
path.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value;
}
var data = { "seamark:name": "Z-2", "seamark:type": "buoy_lateral", "seamark:light:range": "5", "seamark:light:colour": "red", "seamark:light:character": "Q", "seamark:radar_reflector": "yes", "seamark:buoy_lateral:shape": "can", "seamark:buoy_lateral:colour": "red", "seamark:buoy_lateral:system": "iala-a", "seamark:buoy_lateral:category": "port" };
Object
.keys(data)
.forEach(k => {
var keys = k.split(':');
if (keys.length === 1) return;
setValue(data, k.split(':'), data[k]);
delete data[k];
});
console.log(data);
You can also use "for..of" and "Array.reduce" like below
var obj = {
"seamark:name": "Z-2",
"seamark:type": "buoy_lateral",
"seamark:light:range": "5",
"seamark:light:colour": "red",
"seamark:light:character": "Q",
"seamark:radar_reflector": "yes",
"seamark:buoy_lateral:shape": "can",
"seamark:buoy_lateral:colour": "red",
"seamark:buoy_lateral:system": "iala-a",
"seamark:buoy_lateral:category": "port"
}
let newObj = {}
for(let [key, val] of Object.entries(obj)) {
let keys = key.split(':')
keys.reduce((o, d, i) => (
i == keys.length - 1
? (o[d] = val)
: (o[d] = o[d] || {})
, o[d])
, newObj)
}
console.log(newObj)

how do i rename key using 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));

How to convert object containing Objects into array of objects

This is my Object
var data = {
a:{"0": "1"},
b:{"1": "2"},
c:{"2": "3"},
d:{"3": "4"}
};
This is the output that I expect
data = [
{"0": "1"},
{"1": "2"},
{"2": "3"},
{"3": "4"}
]
This works for me
var newArrayDataOfOjbect = Object.values(data)
In additional if you have key - value object try:
const objOfObjs = {
"one": {"id": 3},
"two": {"id": 4},
};
const arrayOfObj = Object.entries(objOfObjs).map((e) => ( { [e[0]]: e[1] } ));
will return:
[
{
"one": {
"id": 3
}
},
{
"two": {
"id": 4
}
}
]
var data = {
a:{"0": "1"},
b:{"1": "2"},
c:{"2": "3"},
d:{"3": "4"}
};
var myData = Object.keys(data).map(key => {
return data[key];
})
This works for me
The accepted answer doesn't take into account the OP wanted to get rid of the keys. This returns only the objects, not their parent key.
Object.entries(ObjOfObjs).map(e => e[1]) outputs:
[
{"0": "1"},
{"1": "2"},
{"2": "3"},
{"3": "4"}
]
You can easily do this by using Object.values() function
var data = {
a:{"0": "1"},
b:{"1": "2"},
c:{"2": "3"},
d:{"3": "4"}
};
console.log(Object.values(data))
You would have to give a name to each value in the object.
Once you fix the first object, then you can do it using push.
var data = {
1: {"0": "1"},
2: {"1": "2"},
3 : {"2": "3"},
4: {"3": "4"}
};
var ar = [];
for(item in data){
ar.push(data[item]);
}
console.log(ar);
http://jsfiddle.net/nhmaggiej/uobrfke6/
this is simple and will do in an immutable way so that your main data not touched but you can create a new mappedData as per your requirement and create a new array.
let data = {
a: { "0": "1" },
b: { "1": "2" },
c: { "2": "3" },
d: { "3": "4" }
};
const mappedDataArray = [];
for (const key in data) {
const mappedData = {
...data[key]
};
mappedDataArray.push(mappedData);
}
console.log(mappedDataArray);
console.log(data);
var array = [];
for(var item in data){
// this condition is required to prevent moving forward to prototype chain
if(data.hasOwnProperty(item)){
array.push(data[item]);
}
}
Finally, It works for me to convert from object to array of objects when you get object value from
const snapshortObject = snapshot.val(); // And they look like this are stored value.
let snapshortObject = {
a: {
message: "Hiiii",
senderId: "tQusPaBhoJXcu2ezlsDxQMUTLCq1",
timestamp: "Wed Jun 8 18:16:18 2022"
},
b: {
message: "Hiiii",
senderId: "tQusPaBhoJXcu2ezlsDxQMUTLCq1",
timestamp: "Wed Jun 8 18:16:18 2022"
},
c: {
message: "Hello 👋👋👋👋",
senderId: "tQusPaBhoJXcu2ezlsDxQMUTLCq1",
timestamp: "Wed Jun 8 18:16:50 2022"
},
d: {
message: "Hello 👋👋👋👋",
senderId: "tQusPaBhoJXcu2ezlsDxQMUTLCq1",
timestamp: "Wed Jun 8 18:16:50 2022"
}
};
const mappedDataArray = [];
slno=1
for (const key in snapshortObject) {
const mappedData = {
...snapshortObject[key],
slno:slno++
};
mappedDataArray.push(mappedData);
}
console.log(mappedDataArray);
I get what you want ! Here is your solution,
var dataObject=[{name:'SrNo',type:'number'}];
And to access or store the array use
dataObject[0].srno=1;
dataObject[0].srno=2;
Hope this is what you needed.
This worked for me. And it seems to be well supported.
toArray(obj_obj) {
return Object.keys(obj_obj).map(i => obj_obj[i]);
}
https://medium.com/chrisburgin/javascript-converting-an-object-to-an-array-94b030a1604c
We can use Object default methods (Object.assign(), Object.values()) to convert Object of Object to array in the following way
const ObjValue = {
a:{"0": "1"},
b:{"1": "2"},
c:{"2": "3"},
d:{"3": "4"}
}
const ObjtoArray = (obj) => Object.assign([], Object.values(obj))
console.log(ObjtoArray(ObjValue))

Categories