Related
So I need a deepSet() function in my React application and I know there are dozens of libraries available for that. However, my requirements are beyond that of the standard deepSet(). My function has to be able to support Arrays, and multiple Arrays in the path.
Example, simple deepSet()
var obj = { one: { two: {three: 'a'}} };
deepSet(obj, 'one.two.three', 'yay');
// {one: {two: { three: 'yay' } } }
What I need it to support (and have working)
var obj = { one: { two: [{three: 'a'}, {three: 'a'}] } };
deepSet(obj, 'one.two[].three', 'yay');
// { one: { two: [{three: 'yay'}, {three: 'yay'}] }};
What I also need it to support, and DO NOT have working yet
var obj = { one: { two: [{three: [{four:'a'}, {four:'b'}]}, {three: [{four:'a'}, {four:'b'}]}]}};
deepSet(obj, 'one.two[].three[].four', 'yay');
// { one: { two: [{three: [{four:'yay'}, {four:'yay'}]}, {three: [{four:'yay'}, {four:'yay'}]}]}};
My problem is that I can't figure out how to get that next level of arrays and iterate over them. I think a recursive approach is best here, but I can't figure that out to handle 2 or more Arrays. I've spent a few hours on this and am turning to SO for help.
Here's the algorithm I have so far, that supports 0 and 1 level of Arrays.
const deepSet = (object, path, value) => {
let fields = path.split('.');
for (let i=0; i<fields.length; i++) {
let f = fields[i];
if (f.indexOf("[]") > -1) {
let arrayfield = f.replace('[]', '');
f = fields[++i];
object[arrayfield].forEach((el, idx) => {
if (isEmpty(el[f])) {
el[f]= {};
}
if (i === fields.length - 1) {
el[f] = value;
}
});
object = object[arrayfield];
}
else {
if (isEmpty(object[f])) {
object[f] = {};
}
if (i === fields.length - 1) {
object[f] = value;
}
object = object[f];
}
};
}
You need to walk through branches as you find these, so that each branch entry becomes a new deepSet.
Example
const deepSet = (obj, path, value) => {
const re = /(\.|\[\]\.)/g;
let i = 0, match = null;
while (match = re.exec(path)) {
const sep = match[0];
const {length} = sep;
const {index} = match;
obj = obj[path.slice(i, index)];
i = index + length;
if (1 < length) {
path = path.slice(i);
obj.forEach(obj => {
deepSet(obj, path, value);
});
return;
}
}
obj[path.slice(i)] = value;
};
var obj = { one: { two: [{three: [{four:'a'}, {four:'b'}]}, {three: [{four:'a'}, {four:'b'}]}]}};
deepSet(obj, 'one.two[].three[].four', 'yay');
This will produce the expected result:
{
"one": {
"two": [
{
"three": [
{
"four": "yay"
},
{
"four": "yay"
}
]
},
{
"three": [
{
"four": "yay"
},
{
"four": "yay"
}
]
}
]
}
}
Hope it helps or, at least, it gave you a hint đź‘‹
You could take a recursive approach
const
deepSet = (object, path, value) => {
let [key, ...keys] = path.split('.');
if (key.endsWith('[]')) {
object = object[key.slice(0, -2)];
Object.keys(object).forEach(k => {
if (keys.length) deepSet(object[k], keys.join('.'), value);
else object[k] = value;
});
} else {
if (keys.length) deepSet(object[key], keys.join('.'), value);
else object[key] = value;
}
},
object = { one: { two: [{ three: [{ four: 'a' }, { four: 'b' }] }, { three: [{ four: 'a' }, { four: 'b' }] }] } };
deepSet(object, 'one.two[].three[].four', 'yay');
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I have got a function that produces an array that is made up of X amount of sub-arrays containing Y amount of objects. Both of these factors are passed to a function to produce an array that looks something like this:
[
[ { '0': 3 }, { '1': 4 }, { '2': 6 }, 'Estimate:': '0jvyt8a' ],
[ { '0': 4 }, { '1': 6 }, { '2': 3 }, 'Estimate:': 'mc973fs' ],
[ { '0': 4 }, { '1': 1 }, { '2': 3 }, 'Estimate:': 'vwsfh8k' ],
[ { '0': 4 }, { '1': 3 }, { '2': 5 }, 'Estimate:': 'n6xzge3' ],
[ { '0': 8 }, { '1': 7 }, { '2': 1 }, 'Estimate:': 'v0jn7bh' ]
]
My question is, is there a way I can convert this array from this structure. To a structure shown below:
[
[1,{1: "vwsfh8k"}, {2: "v0jn7bh"}]
[3,{1: "0jvyt8a"}, {2: "mc973fs"}, {3:"vwsfh8k"}, {4:"n6xzge3"}]
]
Basically, my aim is to take the original array generated by the script (see below) and pass it through another function to record how many times each number was present and what it's 'estimate' number was.
In this example, I just created random numbers between 0 and 10 so an option would be to iterate and count each value I guess but unfortunately, I can't do this because eventually I will be using 5-letter combinations instead of numbers but numbers were easiest to show for an example and proof of concept.
So, I guess, I need to get an array of each unique value and then look at each value up in the original array to find out what estimate IDs have it present. Unfortunately, I don't have even an idea of where, to begin with, this, so I was hoping you guys can help.
Code to generate random array:
// Making an empty array
const arr = [];
//Generating the estimate IDs and placing them all in their own object in their own array.
function estimateGen(length, nodes) {
for (var i = 0; i < length; i++) {
const estimate = [];
let estimateVal = Math.random().toString(36).replace('0.','').slice(0,7);
estimate[`Estimate:`] = estimateVal;
arr.push(estimate);
nodeGen(estimate, nodes)
}
}
// Adding x amount of nodes between 1 and 10 into each estimate sub-array in their own objects.
function nodeGen(estimate, nodes) {
for (var i = 0; i < nodes; i++) {
const node = {};
let nodeID = Math.floor(Math.random() * 10) + 1;
node[i] = nodeID;
estimate.push(node);
}
}
// Calling the function and saying how many nodes per estimate we want.
estimateGen(5, 3);
console.log(arr);
If you have any suggestions on how to improve this code or as to why the estimate values in the sub-array are always last in the array that would be very helpful.
Thank you
--- EDIT ---
I have changed the code that generates the original array to produce a simpler array.
// Making an empty array
const arr = [];
//Generating the estimate IDs and placing them all in their own object in their own array.
function estimateGen(length, nodes) {
for (var i = 0; i < length; i++) {
const estimate = [];
let estimateVal = Math.random().toString(36).replace('0.','').slice(0,7);
estimate.push(estimateVal);
arr.push(estimate);
nodeGen(estimate, nodes)
}
}
// Adding x amount of nodes between 1 and 10 into each estimate sub array in their own objects.
function nodeGen(estimate, nodes) {
for (var i = 0; i < nodes; i++) {
let nodeID = Math.floor(Math.random() * 10) + 1;
estimate.push(nodeID);
}
}
// Calling the function and saying how many nodes per estimate we want.
estimateGen(5, 3);
console.log(arr);
From this code I now get the result:
[
[ 'p68xw8h', 5, 4, 6 ],
[ 'wn2yoee', 5, 4, 5 ],
[ '1w01tem', 9, 7, 4 ],
[ 'we3s53f', 8, 8, 8 ],
[ '5nrtp09', 3, 3, 8 ]
]
Would there be a way to count the number of times the values on the right appear and what 'estimate' ID at [0] it appears in?
Thank you.
First, let's redesign your input data and results to be a more useful format:
// input
[
{ nodes: [3, 4, 6], Estimate: '0jvyt8a' },
{ nodes: [4, 6, 3], Estimate: 'mc973fs' },
{ nodes: [4, 1, 3], Estimate: 'vwsfh8k' },
{ nodes: [4, 3, 5], Estimate: 'n6xzge3' },
{ nodes: [8, 7, 1], Estimate: 'v0jn7bh' }
];
// result
{
1: ["vwsfh8k", "v0jn7bh"],
3: ["0jvyt8a", "mc973fs", "vwsfh8k", "n6xzge3"],
...
]
Then the code would be:
const input = [
{ nodes: [3, 4, 6], Estimate: '0jvyt8a' },
{ nodes: [4, 6, 3], Estimate: 'mc973fs' },
{ nodes: [4, 1, 3], Estimate: 'vwsfh8k' },
{ nodes: [4, 3, 5], Estimate: 'n6xzge3' },
{ nodes: [8, 7, 1], Estimate: 'v0jn7bh' }
];
const result = {};
input.forEach(({
nodes,
Estimate: e
}) =>
nodes.forEach(n => {
if (!result[n]) {
result[n] = [];
}
result[n].push(e);
})
);
console.log(result);
You can create the data with:
// Making an empty array
const arr = [];
//Generating the estimate IDs and placing them all in their own object in their own array.
function estimateGen(length, nodes) {
for (var i = 0; i < length; i++) {
let estimateVal = Math.random().toString(36).replace('0.', '').slice(0, 7);
const estimate = {
Estimate: estimateVal,
nodes: []
}
arr.push(estimate);
nodeGen(estimate, nodes)
}
}
// Adding x amount of nodes between 1 and 10 into each estimate sub array in their own objects.
function nodeGen(estimate, nodes) {
for (var i = 0; i < nodes; i++) {
let nodeID = Math.floor(Math.random() * 10) + 1;
estimate.nodes.push(nodeID);
}
}
// Calling the function and saying how many nodes per estimate we want.
estimateGen(5, 3);
console.log(arr);
I've reformatted your array. The output is different, but you can still use it.
var arr = [
{ '0': 3 , '1': 4 , '2': 6 , 'Estimate:': '0jvyt8a' },
{ '0': 4 , '1': 6 , '2': 3 , 'Estimate:': 'mc973fs' },
{ '0': 4 , '1': 1 , '2': 3 , 'Estimate:': 'vwsfh8k' },
{ '0': 4 , '1': 3 , '2': 5 , 'Estimate:': 'n6xzge3' },
{ '0': 8 , '1': 7 , '2': 1 , 'Estimate:': 'v0jn7bh' }
];
var num = [1, 3, 4, 5, 6, 7, 8];
num = num.map(n =>
[n, ...(
arr.filter(a => [0, 1, 2].some(nm => a[nm] === n))
.map(v => v["Estimate:"])
)]);
console.log(num);
For getting a counting object you could take the values as key and estimates as key for the count of same values.
function estimateGen(length, nodes) {
var array = [];
for (var i = 0; i < length; i++) {
array.push([Math.random().toString(36).replace('0.','').slice(0,7), ...nodeGen(nodes)]);
}
return array;
}
function nodeGen(nodes) {
var result = [];
for (var i = 0; i < nodes; i++) {
result.push(Math.floor(Math.random() * 10) + 1);
}
return result;
}
function count(data) {
return data.reduce((r, [estimate, ...values]) => {
values.forEach(v => {
r[v] = r[v] || {};
r[v][estimate] = (r[v][estimate] || 0) + 1;
});
return r;
}, {});
}
var temp = estimateGen(5, 3);
console.log(temp);
console.log(count(temp));
.as-console-wrapper { max-height: 100% !important; top: 0; }
I have an Object like this:
const val = {"abc":{"1":1, "2":6,"3":5},"def":{"1":3, "2":4,"3":8},"xyz":{"1":5, "2":6,"3":7}}
I want to transform the object data like below:
[{"abc":1,"def":3,"xyz":5},{"abc":6,"def":4,"xyz":6}, ...]
All the values are dynamic, any number of inner object may be there
I have tried like this:
const val = {"abc":{"1":1, "2":6,"3":5},"def":{"1":3, "2":4,"3":8},"xyz":{"1":5, "2":6,"3":7}}
let dataObj = {};
let secondArr = [];
let dataArr =[]
Object.entries(val).map(firstObj=>{
Object.entries(firstObj[1]).forEach(secondObj => {
dataObj={[firstObj[0]]:secondObj[1]};
secondArr.push(dataObj);
})
dataArr.push(secondArr)
})
console.log(dataArr)
Can anyone tell me a solution for this?
Thanks in advance
You could iterate the entries of the objects and take the inner keys as indices of the array with new objects with outer key and value.
var data = { abc: { 1: 1, 2: 6, 3: 5 }, def: { 1: 3, 2: 4, 3: 8 }, xyz: { 1: 5, 2: 6, 3: 7 } },
result = Object
.entries(data)
.reduce((r, [k, o]) => {
Object.entries(o).forEach(([i, v]) =>
Object.assign(r[i - 1] = r[i - 1] || {}, { [k]: v }));
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I've taken the following sample from a different question. And I am able to identify the object. But I also need to find our the position of that object. For example:
var arr = [{
Id: 1,
Categories: [{
Id: 1
},
{
Id: 2
},
]
},
{
Id: 2,
Categories: [{
Id: 100
},
{
Id: 200
},
]
}
]
If I want to find the object by the Id of the Categories, I can use the following:
var matches = [];
var needle = 100; // what to look for
arr.forEach(function(e) {
matches = matches.concat(e.Categories.filter(function(c) {
return (c.Id === needle);
}));
});
However, I also need to know the position of the object in the array. For example, if we are looking for object with Id = 100, then the above code will find the object, but how do I find that it's the second object in the main array, and the first object in the Categories array?
Thanks!
Well, if every object is unique (only in one of the categories), you can simply iterate over everything.
var arr = [{
Id: 1,
Categories: [{Id: 1},{Id: 2}]
},
{
Id: 2,
Categories: [{Id: 100},{Id: 200}]
}
];
var needle = 100;
var i = 0;
var j = 0;
arr.forEach(function(c) {
c.Categories.forEach(function(e) {
if(e.Id === needle) {
console.log("Entry is in position " + i + " of the categories and in position " + j + " in its category.");
}
j++;
});
j = 0;
i++;
});
function findInArray(needle /*object*/, haystack /*array of object*/){
let out = [];
for(let i = 0; i < haystack.lenght; i++) {
if(haystack[i].property == needle.property) {
out = {pos: i, obj: haystack[i]};
}
}
return out;
}
if you need the position and have to filter over an property of the object you can use a simple for loop. in this sample your result is an array of new object because there can be more mathches than 1 on the value of the property.
i hope it helps
Iterate over the array and set index in object where match found
var categoryGroups = [{
Id : 1,
Categories : [{
Id : 1
}, {
Id : 2
},
]
}, {
Id : 2,
Categories : [{
Id : 100
}, {
Id : 200
},
]
}
]
var filterVal = [];
var needle = 100;
for (var i = 0; i < categoryGroups.length; i++) {
var subCategory = categoryGroups[i]['Categories'];
for (var j = 0; j < subCategory.length; j++) {
if (subCategory[j]['Id'] == findId) {
filterVal.push({
catIndex : i,
subCatIndex : j,
id : needle
});
}
}
}
console.log(filterVal);
Here is solution using reduce:
var arr = [{ Id: 1, Categories: [{ Id: 1 }, { Id: 2 }, ] }, { Id: 2, Categories: [{ Id: 100 }, { Id: 200 }, ] } ]
const findPositions = (id) => arr.reduce((r,c,i) => {
let indx = c.Categories.findIndex(({Id}) => Id == id)
return indx >=0 ? {mainIndex: i, categoryIndex: indx} : r
}, {})
console.log(findPositions(100)) // {mainIndex: 1, categoryIndex: 0}
console.log(findPositions(1)) // {mainIndex: 0, categoryIndex: 0}
console.log(findPositions(200)) // {mainIndex: 1, categoryIndex: 1}
console.log(findPositions(0)) // {}
Beside the given answers with fixt depth searh, you could take an recursive approach by checking the Categories property for nested structures.
function getPath(array, target) {
var path;
array.some(({ Id, Categories = [] }) => {
var temp;
if (Id === target) {
path = [Id];
return true;
}
temp = getPath(Categories, target);
if (temp) {
path = [Id, ...temp];
return true;
}
});
return path;
}
var array = [{ Id: 1, Categories: [{ Id: 1 }, { Id: 2 },] }, { Id: 2, Categories: [{ Id: 100 }, { Id: 200 }] }];
console.log(getPath(array, 100));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Hello this is my sample json:
{
"2016-01-01T00:00:00Z": 1,
"2016-02-01T00:00:00Z": 2,
"2016-03-01T00:00:00Z": 3
}
Now I want something like
[
{"Month":"2016-01-01T00:00:00Z", "Number": 1},
{"Month":"2016-02-01T00:00:00Z", "Number": 2},
{"Month":"2016-03-01T00:00:00Z", "Number": 3}
]
How can I do this using JS/Jquery? I wanted to change it to the above mentioned format because I need to put them in html table and I found out that using the second format makes my job easier.
you can do this in the following way
let obj = {
"2016-01-01T00:00:00Z": 1,
"2016-02-01T00:00:00Z": 2,
"2016-03-01T00:00:00Z": 3
};
let result = [];
for(element in obj){
result.push({"Month":element, "Number": obj[element]})
}
console.log(result);
You can use the jQuery map function to change the format of an array.
let jsonArray = {
"2016-01-01T00:00:00Z": 1,
"2016-02-01T00:00:00Z": 2,
"2016-03-01T00:00:00Z": 3
};
var result = $.map(jsonArray, function (item, key) {
return {
Month: key,
Number: item
};
});
You could take the keys with Object.keys and use Array#map for mapping the new objects.
var object = { "2016-01-01T00:00:00Z": 1, "2016-02-01T00:00:00Z": 2, "2016-03-01T00:00:00Z": 3 },
result = Object.keys(object).map(function (k) {
return { Month: k, Number: object[k] };
});
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
var object1 = {
"2016-01-01T00:00:00Z": 1,
"2016-02-01T00:00:00Z": 2,
"2016-03-01T00:00:00Z": 3
};
var finalArray = [];
for (var key in object1) {
if (p.hasOwnProperty(key)) { // p.hasOwnProperty this will check for duplicate key
finalArray.push({
“Month” : key,
“Number”:p[key]
});
}
}
console.log(finalArray)
Another option could include using Object.keys along with map as such...
let obj = {
'2016-01-01T00:00:00Z': 1,
'2016-02-01T00:00:00Z': 2,
'2016-03-01T00:00:00Z': 3
}
let arr = Object.keys(obj).map(key => {
return {'Month': key, 'Number': obj[key]}
});
JSFiddle demo
use $.each for travelling
a = {
"2016-01-01T00:00:00Z": 1,
"2016-02-01T00:00:00Z": 2,
"2016-03-01T00:00:00Z": 3
}
var b = [];
$.each( a, function( key, value ) {
b.push({mounth: key ,number: value });
});
Output will be:
0:{mounth: "2016-01-01T00:00:00Z", number: 1}
1:{mounth: "2016-02-01T00:00:00Z", number: 2}
2:{mounth: "2016-03-01T00:00:00Z", number: 3}