This question already has answers here:
Create an object from an array of keys and an array of values
(9 answers)
Create object from two arrays
(4 answers)
Closed 2 years ago.
Having two arrays:
let values = ["52", "71", "3", "45", "20", "12", "634", "21"];
let names = ["apple", "orange", "strawberry", "banana", "coconut", "pineapple", "watermelon", "plum"];
How can I create an object like:
{
"apple": 52,
"orange": 71,
"strawberry": 3,
"banana": 45,
"coconut": 20,
"pineapple": 12,
"watermelon": 634,
"plum": 21
}
I tried using Object.assign but this only overrides the values.
Object.assign<any, any>(names, values);
Object.defineProperties doesn't work as well or - more likely - I don't know how to use them.
EDIT
I tried the
let temp = {};
names.forEach((item, index) => {
console.log('item: ', item);
console.log('index: ', index);
console.log('temp[item]: ', temp[item]);
console.log('values[index]: ', values[index]);
temp[item] = values[index];
console.log(names);
});
but this is what I got
Create a new result-object. Add to this object foreach element of names a nnew object with name and corresponding value.
Edited: Because it seems tht you have in your values-array all elements as string and in your result-object the values are integers I use parseInt for convertion.
Note: Using a variable name is not so good because you get an TypeError if you want to use anything like this name.forEach, name.map. It seems it's a reserved word or something like this.
let values = ["52", "71", "3", "45", "20", "12", "634", "21"];
let names = ["apple", "orange", "strawberry", "banana", "coconut", "pineapple", "watermelon", "plum"];
let temp = {};
names.forEach((elem, index) => { temp[elem]=parseInt(values[index]) });
names.forEach((item, index) => {
console.log('item: ', item);
console.log('index: ', index);
console.log('temp[item]: ', temp[item]);
console.log('values[index]: ', values[index]);
temp[item] = values[index];
console.log(names);
});
Related
This question already has answers here:
How do I remove all null and empty string values from an object? [duplicate]
(13 answers)
Closed 2 years ago.
I have a JS object here
{
"test1" : "",
"test2" : "apple",
"test3" : "oranges",
"test5" : ""
}
Is there a JS one-liner that can filter out all the properties with empty strings?
Expected result:
{
"test2" : "apple",
"test3" : "oranges",
}
You can do this snippet:
const foo
const bar = Object.fromEntries(Object.entries(foo).filter(value => value[1]))
In bar you have the filtered object.
To understand this, we can split it in three steps:
With the Object.entries(foo) we got a list of foo entries. Each entry is a array with two values, the first one is a key and the second is the value.
With the filter we got all entries in the entries array in the index 1 (the values) and filter if have a value. A empty string is considered a falsie value, so by using value[1] is enough.
For last, with Object.fromEntries we got the filtered entries and we construct a object with this entries. If there is a empty string in foo, after the filter the key value combination isn't in the fromEntries param.
Try this. It will delete all empty property from your original object.
const x = {
"test1" : "",
"test2" : "apple",
"test3" : "oranges",
"test5" : ""
};
Object.keys(x).filter(k => x[k] === '').map(k => delete x[k]);
console.log(x);
You can use Object.fromEntries to rebuild a new filtered object:
var obj = {
"test1": "",
"test2": "apple",
"test3": "oranges",
"test5": ""
};
obj = Object.fromEntries(Object.keys(obj).filter(k => obj[k] !== '').map(k => [k, obj[k]]));
console.log(obj);
I have a JSON response as below:
[{
"id": 1,
"food": {
"fruits": ["Banana", "Orange", "Apple", "Mango"],
"veggies": ["greens", "peppers", "carrot", "potatoes"],
}
},
{
"id": 2,
"food": {
"fruits": ["grapes", "berries", "peach", "pears"],
"veggies": ["cabbage", "spinach"],
"dairy": ["nutmilk", "goatmilk"]
}
}
]
Now i want to merge the Arrays each "id" (1,2 in example) into string ( ; delimited) like below:
id_1 = Banana;Orange;Apple;Mango;greens;peppers;carrot;potatoes
// observer "id_2" has additional array - "dairy"
id_2 = grapes;berries;peach;pears;cabbage;spinach;nutmilk;goatmilk
The key's are dynamic so for some records there are 2 arrays and for some records it can be 3 or 4 and may be 1.
I tried using react/Java Script Array.concat(), but i am not sure how to do it dynamically. Please help me. Thank you.
This is doable easily using Object.values().flat().join(';') demonstrated below:
let arr=[{"id":1,"food":{"fruits":["Banana","Orange","Apple","Mango"],"veggies":["greens","peppers","carrot","potatoes"],}},{"id":2,"food":{"fruits":["grapes","berries","peach","pears"],"veggies":["cabbage","spinach"],"dairy":["nutmilk","goatmilk"]}}];
const result = arr.map(({id,food}) => ({id, food: Object.values(food).flat().join(';')}));
console.log(result);
You may easily restructure the output by simply changing it to e.g. ["id_"+id]: Object.values(...)
First flatten using map, flat and join. Then convert the resulting array of objects to a single object using assign.
var db = [{"id": 1,"food": {"fruits": ["Banana", "Orange", "Apple", "Mango"], "veggies": ["greens","peppers","carrot","potatoes"], }},{"id" : 2,"food": {"fruits": ["grapes", "berries", "peach", "pears" ], "veggies": ["cabbage","spinach"], "dairy": ["nutmilk","goatmilk"]}}];
var flat = db.map(
({id, food}) => ({[`id_${id}`]: Object.values(food).flat().join(';')})
);
var result = Object.assign(...flat);
console.log(result);
This is really two problems: looping through an array of objects to combine them into one object, and looping through an object to concat all of its array.
Tackling the second one first, something like this would work:
const concatArraysInObject = obj =>
Object.values(obj).reduce((result, arr) => result.concat(arr), []);
const input = { a: [1,2,3], b: [4,5,6], c: [7,8,9] };
const output = concatArraysInObject(input);
console.log(output);
Object.values() will give you an array of all arrays in an object.
The reduce() function takes a two parameters: a function and initial value.
The function should also take (at least) 2 parameters: the result of the last call (or initial value) and the current value in the array.
It'll call the function once for each element in the array.
Now, with that solved, we can tackle the first problem.
For this, we can also use reduce() as well, and we'll construct our combined object on each call.
const concatArraysInObject = (obj) =>
Object.values(obj).reduce((result, arr) => result.concat(arr), []);
const mergeObjectsInArray = (arr, dataKey) =>
arr.reduce((result, obj) => ({ ...result, [obj.id]: concatArraysInObject(obj[dataKey]) }), {});
const input = [
{ id: 'A', data: { a: [1,2,3], b: [4,5,6] } },
{ id: 'B', data: { c: [7,8,9], d: [10,11,12] } }
];
const output = mergeObjectsInArray(input, 'data');
console.log(output);
An important note of warning: object key order is NOT guaranteed in JavaScript. While 99% of the time they will be in the order you expect, this is not a guarantee, so if you depend on the order of the keys for the order of the array (if order matters), you'll want to change your input structure. If order doesn't matter, it is probably fine how it is.
Try this using basic for loop. Inside you will compute key dynamically and value being flattened array of Object.values of the iterating object.
var input = [{
id: 1,
food: {
fruits: ["Banana", "Orange", "Apple", "Mango"],
veggies: ["greens", "peppers", "carrot", "potatoes"]
}
},
{
id: 2,
food: {
fruits: ["grapes", "berries", "peach", "pears"],
veggies: ["cabbage", "spinach"],
dairy: ["nutmilk", "goatmilk"]
}
}
];
var temp = [];
for (var i = 0; i < input.length; i++) {
temp.push({
[`id_${input[i].id}`]: Object.values(input[i].food)
.flat(1)
.join(";")
});
}
console.log(temp); // this gives you an array
console.log(Object.assign(...temp));// in case you require one single object
This question already has answers here:
Check if a value is an object in JavaScript
(54 answers)
Closed 3 years ago.
I try to extract Object from bellow array :
var array = [];
array =
a,b,c,{"A":"0","f":"1","g":"2"},{"B":"5","v":"8","x":"4"},{"C":"0","f":"1","g":"2"},c,b
imagine extract this :
result = [
{"A":"0","f":"1","g":"2"},{"B":"5","v":"8","x":"4"},{"C":"0","f":"1","g":"2"}
]
I use my code but didn't give me the right answer :
for (var i =0 ; i < array.length ; i++) {
console.log((array[i].split(','));
}
In this code I just get each variable in each line
I need more thing because in each time maybe I have different
array that has for example 2 Object in this example I just have
3 Object.I try to define If I has any Object I can find them and push them in one array.
You can use Array.filter
var array = [];
array = [
'a','b','c',{"A":"0","f":"1","g":"2"},{"B":"5","v":"8","x":"4"},{"C":"0","f":"1","g":"2"},'c','b'
];
let result = array.filter(e => typeof e === 'object');
console.log(result)
You can use array reduce function. Inside reduce callback check if the type of the element is object then in accumulator array push the element
var array = [];
array = [
'a', 'b', 'c', {
"A": "0",
"f": "1",
"g": "2"
}, {
"B": "5",
"v": "8",
"x": "4"
}, {
"C": "0",
"f": "1",
"g": "2"
},
'c', 'b'
];
let newArr = array.reduce((acc, curr) => {
if (typeof(curr) === 'object') {
acc.push(curr)
}
return acc;
}, []);
console.log(newArr)
I want to count value's number.
Here is json.
x = {"first" : ["apple", "banana", "car", "day"],
"second" : ["apple","car"],
"third" : ["day"],
"fourth" " [],
"fifth" : ["apple"]
}
And I need these output.
object..???['apple']
>>>3
object..???['banana']
>>>1
object..???['car']
>>>2
object..???['day']
>>>2
object..???['elephant']
>>>0
What kind of code should I use?
I tried the following but it isn't working:
Object.values(x['day']).length;
You can get all the values in your object and put them into an array using Object.values() and .flat(). Then, you can .filter() out any items in your values array which are not your desired item. Finally, you can get the .length of this array to find how many items matched your search.
See example below:
const x = {
"first": ["apple", "banana", "car", "day"],
"second": ["apple", "car"],
"third": ["day"],
"fourth": [],
"fifth": ["apple"]
}
const countItem = (obj, search) =>
Object.values(obj).flat().filter(item => item === search).length;
console.log(countItem(x, "apple")); // 3
console.log(countItem(x, "banana")); // 1
console.log(countItem(x, "car")); // 2
console.log(countItem(x, "day")); // 2
console.log(countItem(x, "elephant")); // 0
Use flat() to flatten out the object's values and then use a reduce operation to calculate the number of times the key appears in the object:
const x = {
"first": ["apple", "banana", "car", "day"],
"second": ["apple", "car"],
"third": ["day"],
"fourth": [],
"fifth": ["apple"]
};
const count = (k) => Object.values(x).flat().reduce((a, v) => a + (k === v ? 1 : 0), 0);
console.log(count('day')); // 2
I have two arrays of objects:
[
0: {key1: value1, key2: value2, key3: value3},
1: {key1: value1, key2: value2, key3: value3}
]
[
0: {stop_id: 173, file_id: "1", key_type: null, key_value: "0020", seg_beg: 32},
1: {stop_id: 176, file_id: "1", key_type: null, key_value: "0201", seg_beg: 10},
2: {stop_id: 176, file_id: "1", key_type: null, key_value: "0201", seg_beg: 10}
]
I need to check to see if the values of any of the keys in the first object, match any of the values of the key_value...keys, in the second object, and then set a variable further up to the stop_id value in the matched record. Like this:
if(object1.value === object2.key_value){
match = object2[iterator].stop_id;
}
To simplify this, I have attempted to just grab the values of the first object:
//pd.segs is object 1
let pdSegValues = [];
for(let i=0;i<pd.segs.length;i++){
pdSegValues.push(Object.values(pd.segs[i]));
}
But that gets me an array of arrays again, and basically puts me back in the same situation. I'm suffering from a fried brain, and admittedly have a weakness for loops. Can anyone show me a decent way to accomplish what I need here?
You can do this by collecting the values you want to test and then using some.
let arr1 = [
{"a1": "value1", "b1": "value2"},
{"a2": "0020", "b2": "value22"},
{"a3": "value111", "b3": "0201"}
];
let arr2 = [
{stop_id: 173, file_id: "1", key_type: null, key_value: "0020", seg_beg: 32},
{stop_id: 176, file_id: "1", key_type: null, key_value: "0201", seg_beg: 10},
{stop_id: 176, file_id: "1", key_type: null, key_value: "0201", seg_beg: 10}
];
// accumulate unique arr1 values to an array
let arr1Values = Array.from(arr1.reduce((acc, curr) => {
Object.values(curr).forEach(v => acc.add(v));
return acc;
}, new Set()));
// accumulate all unique arr2 "key_value"
let arr2KeyValues = arr2.reduce((acc, curr) => {
acc.add(curr.key_value);
return acc;
}, new Set());
console.log(arr1Values);
console.log(Array.from(arr2KeyValues));
// Test if any of the values in objects in the first array are
// equal to any of the key_values in the second array
console.log(arr1Values.some(k => arr2KeyValues.has(k)));
It looks like you're going to have to compare every object in one array to every object's keys in another array. An initial brute force approach has 3 nested for loops:
// Loop through the objects in the first array
for (const objectA of arrayA) {
// Loop through that object's keys
for (const key in objectA) {
// Loop through the objects in the second array
for (const objectB of arrayB) {
if (objectA[key] === objectB.key_value) {
// do all the stuff
}
}
}
}
Here's what I ended up doing, just to leave a record :)
let stopRules = pd.stopRules;
let pdSegs = pd.segs;
let routeStopsTest = [];
//Returns a flat array of all unique values in first object
//Thanks #slider!
let pdSegValues = Array.from(pdSegs.reduce((acc, curr) => {
Object.values(curr).forEach(v => acc.add(v));
return acc;
}, new Set()));
//Pushes all objects from stopRules array to a holding array
//When they match individual segments in the pdSegs array
pdSegValues.forEach( seg => {
let nullTest = stopRules.filter(o => o.key_value === seg);
if(nullTest.length !== 0){
routeStopsTest.push(nullTest);
}else{}
});
Then all I have to do is flatten the resulting array of objects, and I have the results I need, which I can then loop through for the original purpose.
Thank you, everyone, for the insightful input. I've learned a fair bit here :)