I have been trying to convert this data:
var myArray = [
[1,2,3,4],
["1","2","3","4"],
["a", "b", "c", "d"]
]
to this:
var result = [
{
"num": 1,
"str": "1",
"let": "a"
},
{
"num": 2,
"str": "2",
"let": "b"
},
{
"num": 3,
"str": "3",
"let": "c"
},
{
"num": 4,
"str": "4",
"let": "d"
}
]
Any assistance will be extremely helpful. I have tried various iterations but none of them yield what I am hoping for.
I am trying to use this:
objectified_data = array_data.map(function(x) {
return {
"num": x[0],
"str": x[1],
"let": x[2]
}
})
But I cannot figure out how to make the homogenous set of array, heterogenous for this to work. Ultimately, I am trying to filter out certain keys, so the original data as it was is not working for that task
You can achieve this with a simple for
var myArray = [
[1, 2, 3, 4],
["1", "2", "3", "4"],
["a", "b", "c", "d"]
]
const json = [];
for (let i = 0; i < myArray[0].length; i++) {
json.push({
num: myArray[0][i],
let: myArray[1][i],
str: myArray[2][i],
});
}
console.log(json);
Try this
var myArray = [[1,2,3,4],["1","2","3","4"],["a", "b", "c", "d"]];
let result = myArray[0].map((v, i) => ({
"num": myArray[0][i],
"let": myArray[1][i],
"str": myArray[2][i]
}))
console.log(result)
Just a basic solution. You would want i to be dynamic I believe ? In that case you can just check the first nested array's size and use that as i.
let x = 0;
let y = 1;
let z = 2;
let json = [];
for(let i=0; i<4;i++){
let item = {};
item = {
["num"]: myArray[x][i],
["let"]: myArray[y][i],
["str"]: myArray[z][i]
}
result.push(item);
}
Related
I'm trying to build a list of all the unique levels in a multidimensional array of objects.
Assuming this data...
let levels = [
["P", "B", "L"],
["A", "B", "L3"],
["A", "B", "L3"],
["P", "B", "M"],
["P", "C", "L"],
["A", "C", "L3"]
];
I need to end up with an array structure like this:
const result = [
[ 1, 'P', 11, 'P.B', 111, 'P.B.L' ],
[ 1, 'P', 11, 'P.B', 112, 'P.B.M' ],
[ 1, 'P', 12, 'P.C', 121, 'P.C.L' ],
[ 2, 'A', 21, 'A.B', 211, 'A.B.L3' ],
[ 2, 'A', 22, 'A.C', 221, 'A.C.L3' ]
];
Note:
Where each entry is an array of a unique level.
Level ids:
1 => level 1
11 => level 1 and its sub level
111 => level 1, its sub level and sub level's level
On each new level 1 the id will increment as follows for other sub-levels and sub level's level:
2 => new level 1
21 => new level 1 and its new sub-level
211 => new level 1, its new sub-level and new sub level's level
I'm having real trouble calculating the level ids for each unique pair.
So far I have tried to return the unique pairs only as below:
function updateLevels(levels) {
const { result } = levels.reduce(
(acc, crr) => {
const l1Key = crr[0];
const l2Key = `${l1Key}.${crr[1]}`;
const l3Key = `${l2Key}.${crr[2]}`;
if (!acc.checkMap[l3Key]) {
acc.checkMap[l3Key] = true;
acc.result.push([l1Key, l2Key, l3Key]);
}
return acc;
},
{
checkMap: {},
result: [],
}
);
return result;
}
const result =
[
[ 'P', 'P.B', 'P.B.L' ],
[ 'A', 'A.B', 'A.B.L3' ],
[ 'P', 'P.B', 'P.B.M' ],
[ 'P', 'P.C', 'P.C.L' ],
[ 'A', 'A.C', 'A.C.L3' ]
]
Basically this solution needs two steps:
Get an array with numbers and connected strings.
You could take an object for keeping the level information and check if the actual data set exists with a flag add for pushing a new array to the result set.
Sort the result by taking odd indices of the array.
const
getUnique = array => {
const levels = { _: 0, data: [] };
return array
.reduce((r, a) => {
let add = false;
const
temp = [],
final = a.reduce((l, v, i, a) => {
if (!l[v]) {
l[v] = {
_: 0,
data: [(l.data[0] || 0) * 10 + ++l._, (l.data[1] || '' ) + (l.data[1] ? '.' : '') + v]
};
add = true;
}
temp.push(...l[v].data);
return l[v];
}, levels);
if (add) r.push(temp);
return r;
}, [])
.sort((a, b) => {
let i = 0, r = 0;
while (i < a.length && !r) {
r = a[i] - b[i];
i += 2;
}
return r;
});
},
levels = [["P", "B", "L"], ["A", "B", "L3"], ["A", "B", "L3"], ["P", "B", "M"], ["P", "C", "L"], ["A", "C", "L3"]],
result = getUnique(levels);
result.forEach(a => console.log(...a));
I am stuck in a situation.
I have an array
arr: [
{
"a": "1"
},
{
"b": "4"
},
{
"c": "6"
},
{
"d": "9"
}
]
and an array
[a,c]
I want my output an array which have only a and c as per array. Can someone please suggest.
Output desired
arr: [
{
"a": "1"
},
{
"c": "6"
}
]
You have to apply a filter to arr1 and check if the key of arr1 is there in arr2 like:
let arr1 = [
{
a: '1'
},
{
b: '4'
},
{
c: '6'
},
{
d: '9'
}
];
let arr2 = ['a', 'c'];
let result = arr1.filter(item => arr2.includes(Object.keys(item)[0]));
alert(JSON.stringify(result));
I think you have to do something like this
let arr1 = [
{
"a": "1"
},
{
"b": "4"
},
{
"c": "6"
},
{
"d": "9"
}
];
let arr2 = ["a","c"];
let result = []
for(let obj of arr1){
for(let key of arr2){
if(obj.hasOwnProperty(key)){
result.push(obj);
break;
}
}
}
alert(JSON.stringify(result));
I am trying to "sum" the items from one array to another, preserving their children (subarrays):
array1 = [ array2 = [ array3 = [
[ [ [
"A", "1", "A",
"B", "2", "B",
[ [ "1",
"C" + "3" = "2",
] ] [
], ], "C",
"D" "4" "3"
] ] ]
],
"D",
"4"
]
Edit: Ideally the longest array would be treated as the "main" array (its values would come before the shortest array).
If the arrays have the same number of elements, the first array is the main.
["a", ["b", "c"], "d"]
+
["x", ["v", "w"], "y"]
=
["a" "x", ["b", "c", "v", "w"], "d", "y"]
["a", "b", ["c", "d", ["e", "f"]]]
+
[["1", ["2"]]]
=
["a", "b", ["c", "d", "1", ["e", "f", "2"]]]
Would it be possible? so far the only suggestions I've found are related to the use of .concat(), however it concatenates one array at the end of the other, and does not merge both:
var array1 = [["A", "B", ["C"]], "D"];
var array2 = [["1", "2", ["3"]], "4"];
console.log(array1.concat(array2)) // returns [["A", "B", ["C"]], "D", ["1", "2", ["3"]], "4"]
Edit 2:
I've been thinking about the problem in a different way now, and realized that an easy way to visualize it is like this:
target = [
"A",
"B",
[
"C",
"D",
[
"E"
],
"J"
]
]
I want to add the following element after "E":
newelement = [
[
[
"F",
[
"G",
"H",
"I"
]
]
]
]
the result would be:
result = [
"A",
"B",
[
"C",
"D",
[
"E",
"F",
[
"G",
"H",
"I"
]
],
"J"
]
]
so that's basically it, merging one array with another.
If I understand correctly you want to concat subsections of both arrays that consist only of non-arrays (the number of elements may differ), then merge the next arrays of both recursively, and then apply again the first logic to the next subsections having no arrays... etc.
Here is that idea implemented:
function deepConcat(a, b) {
if (a.length < b.length) return deepConcat(b, a);
let i = 0, j = 0, result = [];
while (true) {
while (i < a.length && !Array.isArray(a[i])) result.push(a[i++])
while (j < b.length && !Array.isArray(b[j])) result.push(b[j++])
if (i >= a.length || j >= b.length) break;
result.push(deepConcat(a[i++], b[j++]));
}
return [...result, ...a.slice(i), ...b.slice(j)];
}
const test = (a, b) => console.log(JSON.stringify(deepConcat(a, b)));
test([["A", "B", ["C"]], "D"], [["1", "2", ["3"]], "4"]);
test(["a", ["b", "c"], "d"], ["x", ["v", "w"], "y"]);
test(["a", "b", ["c", "d", ["e", "f"]]], [["1", ["2"]]]);
test(["A","B",["C","D",["E"],"J"]], [[["F",["G","H","I"]]]]);
Something like this?
array1 = [
["A", "B", ["C"]], "D"
]
array2 = [
["1", "2", ["3"]], "4"
]
array3 = [
["A", "B", "1", "2", ["C", "3"]], "D", "4"
]
const findFirstNonPrimitiveIndex = arr => arr.findIndex(x => !isPrimitive(x))
const takePrimitives = (arr, pos = 0) => arr.slice(0, findFirstNonPrimitiveIndex(arr))
const isPrimitive = x => typeof x !== "object"
const merge = (arr1, arr2) => {
const [head1, ...rest1] = arr1
const [head2, ...rest2] = arr2
// base case
if (rest1.length === 0)
if (isPrimitive(head1)) return [head1, head2];
else return [merge(head1, head2)]
// inductive step
if (isPrimitive(head1)) {
const cutPoint = findFirstNonPrimitiveIndex(rest1);
return [
...takePrimitives(arr1),
...takePrimitives(arr2),
...merge(rest1.slice(cutPoint), rest2.slice(cutPoint))
]
} else {
return [merge(head1, head2), ...merge(rest1, rest2)];
}
}
const result = merge(array1, array2);
console.log(result)
.as-console-wrapper {
top: 0;
max-height: 100% !important;
}
I have an array of an object with dynamic keys
response = [{"1": 1}, {"2": 1}, {"3": 1}, {"4": 0}, {"5": 0}];
I want to flatten this array of an object into a single array
Output = [1, 1, 1, 0, 0]
I tried the following:
const test2 = this.response.map(obj => {
Object.keys(obj).map(function(key){
return obj[key]
})
});
const test = this.response.reduce(function(prev, curr){
console.log(curr)
return (curr) ? prev.concat(curr): prev;
},[]);
You can just use map and object.values
response = [{"1": 1}, {"2": 1}, {"3": 1}, {"4": 0}, {"5": 0}]
const vals = response.map(o => Object.values(o)[0])
console.log(vals)
You can use .map() with .concat():
let data = [{"1": 1}, {"2": 1}, {"3": 1}, {"4": 0}, {"5": 0}];
let result = [].concat(...data.map(Object.values));
console.log(result);
Use reduce and for..in to loop over the object
let response = [{
"1": 1
},
{
"2": 1
},
{
"3": 1
},
{
"4": 0
},
{
"5": 0
}
]
let k = response.reduce(function(acc, curr) {
for (let keys in curr) {
acc.push(curr[keys])
}
return acc;
}, [])
console.log(k)
response = [{"1": 1},{"2": 1},{"3": 1},{"4": 0},{"5": 0}]
var newArray = []
for (element of response) {
Object.keys(element).map(key => {
newArray.push(element[key])
})
}
console.log(newArray)
I've got an object like
var data = [
{
"Name": ["Jane", "Peter", "Jenny"],
"Id": [1, 2, 3],
"Years": [16, 17, 18]
}
];
But I want to put it to a react table which need another format like it
var data1 = [
{
"Name": "Jane",
"Id": 1,
"Years": 16,
},
{
"Name": "Peter",
"Id": 2,
"Years": 17,
},
{
"Name": "Jenny",
"Id": 3,
"Years": 18,
}
]
How can I conversion it with JSX?
Here is the pretty much straight forward implementation for your problem. For iteration, I have considered the length of Name array inside the object.
var data = [{
"Name": ["Jane", "Peter", "Jenny"],
"Id": [1, 2, 3],
"Years": [16, 17, 18]
}];
var data1 = [ ];
var iterations = data[0].Name.length;
var requiredData = data[0];
var keyArray = Object.keys(requiredData);
for ( var i = 0; i < iterations; i++ ) {
tempObj = { };
for (var key of keyArray) {
tempObj[key] = requiredData[key][i];
}
data1.push(tempObj);
}
console.log('data1 = ', data1)
I'd find out the maximum property length (in case they aren't all the same), create an array of that size, iterate in a for-loop, create objects using the data keys and matching index positions (null if there's no match) and push them into the array.
const data = [{
"Name": ["Jane", "Peter", "Jenny"],
"Id": [1, 2, 3],
"Years": [16, 17, 18]
}]
const interestingData = data[0]
const keys = Object.keys(interestingData)
const maxItems = keys.reduce((count, key) => Math.max(count, interestingData[key].length), 0)
const transformed = new Array(maxItems)
for (var i = 0; i < maxItems; i++) {
transformed[i] = keys.reduce((obj, key) => Object.assign(obj, {
[key]: interestingData[key][i] || null // default value if no matching index
}), Object.create(null))
}
console.info(transformed)