Merge values to an array based on similar object key javascript [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
i have a return like this
[
{
"tripw3": "1"
},
{
"tripw1": "2"
},
{
"tripw1": "3"
},
{
"tripw2": "4"
},
{
"tripw2": "5"
},
{
"tripw3": "6"
},
{
"tripw3": "7"
}]
and I want to make the above result be
[
{
tripw3: ["1", "6", "7"],
tripw2: ["4", "5"],
tripw1: ["3", "2"]
}]
Until now I'm still confused to make this happen.

You cane easily acheve the result using reduce, Object.keys and forEach
const arr = [
{
tripw4: "1",
},
{
tripw4: "2",
},
{
tripw4: "3",
},
{
tripw4: "4",
},
{
tripw4: "5",
},
{
tripw4: "6",
},
{
tripw4: "7",
},
];
const result = [arr.reduce((acc, curr) => {
Object.keys(curr).forEach((k) => acc[k] ? acc[k].push(curr[k]) : (acc[k] = [curr[k]]));
return acc;
}, {})];
console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

Convert array of paths into a Tree in JavaScript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 months ago.
Improve this question
Given this input:
const paths = ["src", "src/components", "src/components/index.ts", "src/utils", "src/configuration/config.ts", "another/file.ts"];
I need to create a function or a data structure that returns a Tree with the following structure.
[
{
"id": "src",
"level": 1,
"childrens": [
{
"id": "src/components",
"level": 2,
"childrens": [
{
"id": "src/components/index.ts",
"level": 3,
"childrens": []
}
]
},
{
"id": "src/utils",
"level": 2,
"childrens": []
},
{
"id": "src/configuration",
"level": 2,
"childrens": [
{
"id": "src/configuration/config.ts",
"level": 3,
"childrens": []
}
]
}
]
},
{
"id": "another",
"level": 1,
"childrens": [
{
"id": "another/file.ts",
"level": 2,
"childrens": []
}
]
}
]
I tried everything but I can't make it work, so if anyone can help I would appreciate it a lot.
Thank you.
First, here's the solution based on this answer: https://stackoverflow.com/a/57344801/3807365.
Explanation below.
const paths = ["src", "src/components", "src/components/index.ts", "src/utils", "src/configuration/config.ts", "another/file.ts"];
let agg = {
temp: []
};
paths.forEach(path => {
path.split('/').reduce((agg, part, level, parts) => {
if (!agg[part]) {
agg[part] = {
temp: []
};
agg.temp.push({
id: parts.slice(0, level + 1).join("/"),
level: level + 1,
children: agg[part].temp
})
// console.log(agg)
}
return agg[part];
}, agg)
})
var result = agg.temp;
console.log(result)
.as-console-wrapper {
max-height: 100% !important;
}
Explanation:
Given a path (splitted to parts) and the result which is an empty array []
we are building this kind of object (helper object!):
{
"src" : {
"utils" : {
"file.ts" : {}
},
"components" : {
"file.ts" : {}
}
},
"another": {
"file.ts" : {}
}
}
We do this step by step as we go on each part of the path.
And we do this to each path building this lovely tree.
Simple enough.
But as we do, we are creating arrays in the result object (which is under property temp) - arrays of items of the same level in the format {id, level, children}.
Finally, we ignore this entire helper tree and only return the first level array - which is the result (under property temp).
Once you realize this, you can see the possible error in this method. Can you spot it? What kind of path name will "mess" with the result?

How can I find any item inside a array with objects inside [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 months ago.
Improve this question
I have this data
{playstation: Array(1), freefire: Array(1), pubg: Array(1), roblox: Array(1), steam: Array(1), …}
This is what the arrays look like:
freefire: [{…}]
playstation: [{…}]
pubg: [{…}]
razorgold: [{…}]
roblox: [{…}]
steam: [{…}]
{
"freefire": {
"id": 1,
"attributes": {
"ProductCode": "427",
"createdAt": "2022-06-09T11:29:04.187Z",
"updatedAt": "2022-06-09T11:29:05.518Z",
"publishedAt": "2022-06-09T11:29:05.513Z",
"ProductCodeAlt": "FLASH-427",
"Name": "20",
"FaceValue": 20,
"DefaultCost": 2000,
"Description": "R20 Uber Token",
"Vendor": "Uber",
"VendorId": 15,
}
}
}
I am trying to find anything in that data using this method.
const item = data.freefire.find(
(item) => String(item.ProductCode) === ProductCode
);
It does work only by specifying the item path. I do not want to specify it. I just want to do it like this.
const item = data.find(
(item) => String(item.ProductCode) === ProductCode
);
but is seems not to work
Well, take a look to the following code
const data = {
first: [
{
ProductCode: 1,
otherStuff: "other stuff A"
},
{
ProductCode: 1,
otherStuff: "other stuff B"
},
{
ProductCode: 2,
otherStuff: "other stuff X1"
},
],
second: [
{
ProductCode: 1,
otherStuff: "other stuff C"
},
{
ProductCode: 3,
otherStuff: "other stuff X2"
},
{
ProductCode: 2,
otherStuff: "other stuff X3"
},
]
}
const ProductCode = 1;
const result = Object.keys(data).map(key => data[key].filter(item => item.ProductCode === ProductCode)).flat(1);
console.log(result);
This will log
[
{
"ProductCode": 1,
"otherStuff": "other stuff A"
},
{
"ProductCode": 1,
"otherStuff": "other stuff B"
},
{
"ProductCode": 1,
"otherStuff": "other stuff C"
}
]
Edit
An edit have been made to the answer by changing the structure of the objects, the principle is still the same here.
If you're looking for a single search hit, you can look into each key of the main object, go into its array and search, and finally return your find.
const codeToFind = 3;
const data = {
playstation: [{ productCode: 1 }],
freefire: [{ productCode: 2 }],
pubg: [{ productCode: 3 }],
roblox: [{ productCode: 4 }],
steam: [{ productCode: 5 }],
};
let found;
const result = Object.keys(data).find((key) => data[key].find((subObject) => subObject.productCode === codeToFind));

How to convert two Array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
What is the best way to convert:
["Isolated-1", "SVT_FedPortGroup", "SVT_StoragePortGroup", "VM Network", "test-pg-2002"]
and this :
["target_Isolated-1", "target_SVT_FedPortGroup", "target_SVT_StoragePortGroup","target_VM Network" ,"target_test-pg-2002"];
to:
"NetworkMaps": [
{
"ENVID": null,
"SourcePG": "Isolated-1",
"TargetPG": "target_Isolated-1"
},
{
"ENVID": null,
"SourcePG": "VM Network",
"TargetPG": "target_SVT_FedPortGroup"
}...
]
I need to to merge two array with respective values.
For example
arr1 : ["a", "b", "c"];
arr2 : ["apple", "ball", "cat"];
result : [{source: "a",target: "apple"}, {source: "b",target: "ball"},{source: "c",target: "cat"}]
Just map them per index (if they have the same length) in a simple loop. Here is a demo:
a = ["Isolated-1", "SVT_FedPortGroup", "SVT_StoragePortGroup", "VM Network", "test-pg-2002"]
b = ["target_Isolated-1", "target_SVT_FedPortGroup", "target_SVT_StoragePortGroup", "target_VM Network", "target_test-pg-2002"]
c = {
"NetworkMaps": []
}
for (var i = 0; i < a.length; i++) {
c.NetworkMaps.push({
"ENVID": null,
"SourcePG": a[i],
"TargetPG": b[i]
})
}
console.log(c);

How order a JSON alphabetically in javascript, like this? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I can ordering a-z using the .sort() method in javascript, but I would get a JSON like this: (With a "A-Z" index containing the result)
data: {
"A": [
{
"name": "Anh Tuan Nguyen",
"age": 28
},
{
"name": "An Nguyen",
"age": 20
},
],
"Z": [
{
"name": "Zue Dang",
"age": 22
},
{
"name": "Zoom Jane",
"age": 30
},
]
}
var names = [{name:"a1"},{name:"a2"},{name:"b1"},{name:"b2"}.....];
var data = {};
for (var i = 0; i < names.length; i++) {
var n = names[i].name.subStr(0,1);
if (data[n] == null)
data[n] = [];
data[n].push(names[i]);
}
There is no way to sort a JSON data structure, however, we can do it by using the following process:
Get your data keys with Object.keys(myResults.data)
Sort you keys
Create a reduce function to transform your ordered keys into an ordered object
The snippet is here, I hope it helps:
var myResults = {
data: {
C: [
{
"name": "Kevin Doe",
"age": 22
}
],
A: [
{
"name": "Alex Doe",
"age": 31,
}
],
B: [
{
"name": "Boris Doe",
"age": 22
},
{
"name": "Birdo Doe",
"age": 30
},
]
}
};
var originalData = myResults.data;
// 1. get the keys
var dataKeys = Object.keys(originalData);
// 2. sort the keys
var sortedKeys = dataKeys.sort();
// 3. create the object again
var orderedData = sortedKeys.reduce(function(result, key) {
return Object.assign(
{},
result,
{ [key]: myResults.data[key] }
);
}, {});
document.getElementById('original').innerHTML = JSON.stringify(originalData);
document.getElementById('sorted').innerHTML = JSON.stringify(orderedData);
h3 {
margin: 0;
}
code {
display: block;
margin-bottom: 15px;
padding: 10px;
background-color: #f9f9f9;
}
<h3>Original Data</h3>
<code id="original"></code>
<h3>Ordered Data</h3>
<code id="sorted"></code>
JavaScript objects are not ordered. If you want to iterate over an object's properties, you can sort the keys and then retrieve your values:
const result = {
data: {
Z: [],
F: [],
A: [],
D: []
}
};
Object
.keys(result.data)
.sort()
.map(key => console.log(key, result.data[key]));
UPDATE:
Exist a JavaScript library that make It possible: Lodash Utilities (https://lodash.com/docs/4.17.4). Contain methods for .sort() JSON (no Arrays) and a method to obtain the JSON for I asked in this question. I only did this:
//First, order my JSON alphabetically with _.sortBy method (I can even order by a nested property in my JSON)
var order = _.sortBy(require('./names'), function (el) { return el.name });
//Second, I group my order result by the first letter of my property 'name' in my JSON
var list = _.groupBy(order, (b) => b.name[0].toUpperCase());
This is my input:
[
{"name":"Mark"},
{"name":"Jul"},
{"name":"Alicia"},
]
This is my output:
[
"A": [
{
"name": "Alicia"
}
],
"J": [
{
"name": "Jul"
},
],
"M": [
{
"name": "Mark"
},
]
I hope this help to somebody!

Iterate json data in javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Following JSON data comes from php,
I have tried following code. But console displays undefined error.
jQuery.each(result.address, function(obj) {
console.log(obj.city);
});
EDIT : Also it's not working and throwing undefined error.
jQuery.each(result.address, function(obj) {
console.log(obj[0].city);
});
It is working : console.log(result.address.address1.city);. But in this case address1 is not fixed. eg. result.address.xyz.city, result.address.abc.city
You're calling city on each address, while cities are inside addressX inside address. Try:
jQuery.each(result.address, function(key, val) {
console.log(val.city);
});
jsfiddle DEMO
Maybe in this way:
for (i = 0; i < result.address.length; i++) {
console.log(result.address[i].city);
}
I'm not sure if jquery.each works in this case.
I hope it helps.
Javascript
var dictionary = {
"12Jan2013": [{
"id": "0",
"name": "ABC"
}, {
"id": "1",
"name": "DEF"
}],
"13Jan2013": [{
"id": "0",
"name": "PQR"
}, {
"id": "1",
"name": "xyz"
}]
};
for (var i in dictionary) {
dictionary[i].forEach(function(elem, index) {
console.log(elem, index);
});
}
Output
Object {id: "0", name: "ABC"} 0
Object {id: "1", name: "DEF"} 1
Object {id: "0", name: "PQR"} 0
Object {id: "1", name: "xyz"} 1

Categories