I have an array of objects like,
customer1 = [
{"key": "name",
"value": "Peter"},
{"key": "age",
"value": 23},
{"key": "address",
"value": "xyz St, abcd"},
{"key": "points",
"value": 234}
]
and I want to find say age and address from this object, what is the recommended and optimal way to do that? For real application, I might have 20-40 key-value objects in this array, out of which I might want to access 5-10 values.
What I do right now is I loop through this object and use conditions to find and assign values to my variables. but in this approach, I have to write multiple else if expressions (5-10).
For example,
let name: string;
let points: number;
for (var item of customer1) {
if (item.key === "name") {
name = item.value;
} else if (item.key === "points") {
points = item.value;
}};
You can simply achieve this requirement with the help of Array.filter() along with Array.map() method.
Live Demo :
const customer1 = [
{ "key": "name", "value": "Peter" },
{ "key": "age", "value": 23 },
{ "key": "address", "value": "xyz St, abcd" },
{ "key": "points", "value": 234 }
];
const searchKeys = ['age', 'address'];
const res = customer1.filter(obj => searchKeys.includes(obj.key)).map(({ value}) => value);
const [age, address] = res;
console.log(age);
console.log(address);
You will always have to write explicitly "name", "points",... because you can't parse string value and use it to identify variable with the same name.
But to avoid using multiple else if, maybe the switch case statement is more appropriate and readable?
interface CustomerProperty {
key: string,
value: string | number
}
let customer1: CustomerProperty[] = [
{
"key": "name",
"value": "Peter"
},
{
"key": "age",
"value": 23},
{
"key": "address",
"value": "xyz St, abcd"},
{
"key": "points",
"value": 234
}
];
let nameValue: string;
let pointsValue: number;
for (var item of customer1) {
switch (item.key) {
case "name":
nameValue = item.value as string;
break;
case "points":
pointsValue = item.value as number;
break;
}
};
Related
I have an object
const items = {
"123": {
"key": 123,
"name": "one name",
},
"456": {
"key": 456,
"name": "two name",
},
"789": {
"key": 789,
"name": "three name",
},
};
Need to filter this from below array, with array index as object.key
const myFilter = [123,789];
Code I am trying is as below but it returning array inedx as 0,1,2... but I need the index to be object.key.
let selectedItems = myFilter.map((key) => {
return items[key];
});
Current output :
[0:{
key: 123,
name: "one name"
}, 1: {
key: 789,
name: "three name"
}]
Expected Output
[123:{
key: 123,
name: "one name"
}, 789: {
key: 789,
name: "three name"
}]
jsfiddle - https://jsfiddle.net/kb374exh/2/
Your actual output is actually correct and the only possible result from mapping the myFilter array to the matching properties from items.
const items = {
"123": {
"key": 123,
"name": "one name",
},
"456": {
"key": 456,
"name": "two name",
},
"789": {
"key": 789,
"name": "three name",
},
};
const myFilter = [123, 789];
const selectedItems = myFilter.map((key) => items[key]);
console.log(selectedItems);
The logged output you see is including the array index. You likely are seeing the index included when logging in the browser.
If you want an array of objects where the original key is the new index then the best you can likely do is an array of length <highest key> and a bunch of "holes" that are simply undefined.
const items = {
"123": {
"key": 123,
"name": "one name",
},
"456": {
"key": 456,
"name": "two name",
},
"789": {
"key": 789,
"name": "three name",
},
};
const myFilter = [123, 789];
const selectedItems = Object.entries(items).reduce((selectedItems, [key, value]) => {
if (myFilter.includes(value.key)) selectedItems[key] = value;
return selectedItems;
}, []);
console.log(selectedItems);
If you are ok with the result being an object then you can have more succinct output, you'll basically end up with back with an object with key-value pairs filtered out.
const items = {
"123": {
"key": 123,
"name": "one name",
},
"456": {
"key": 456,
"name": "two name",
},
"789": {
"key": 789,
"name": "three name",
},
};
const myFilter = [123, 789];
const selectedItems = Object.fromEntries(Object.entries(items).filter(([, value]) => myFilter.includes(value.key)));
console.log(selectedItems);
I would like to convert the below array of objects into another form (varname is ignored as its not required, key and value is used to generate the output form). Any leads would be appreciated
Input array:
[
{
"key": "string_U6",
"value": "grandwagoneer",
"varname": "pagenameplate"
},
{
"key": "string_U13",
"value": "2021",
"varname": "year"
}
]
Output
[
{
"string_U6": "grandwagoneer"
},
{
"string_U13": "2021"
}
]
You could try using map as below:
var input = [ { "key": "string_U6", "value": "grandwagoneer", "varname": "pagenameplate" }, { "key": "string_U13", "value": "2021", "varname": "year" } ];
var output = input.map(function(entry){
let obj = {};
obj[entry.key] = entry.value;
return obj;
});
console.log(output);
As the question asked how to convert array object in snowflake, I wanted to share Snowflake way to do it:
-- SQL to create a sample table with data
create table sample_table (v variant )
as select parse_json(' [ { "key": "string_U6", "value": "grandwagoneer", "varname": "pagenameplate" },
{ "key": "string_U13", "value": "2021", "varname": "year" } ]');
-- query to parse the variant and create the array:
select ARRAY_AGG( OBJECT_CONSTRUCT(i.value:key::varchar, i.value:value::varchar) )
from sample_table,
lateral flatten ( sample_table.v ) i;
It will produce exact output you want.
I have the following Json Object
[
{ "key": "age", "value": 81 },
{ "key": "name", "value": "Luis" }
]
I am trying to find the most optimal way to recover this data.
const name = ??????;
What's the best way to extract the "value" of the 'name' key using Javascript? I know one of the ways would be to iterate until I find the value, but I figured there is a more fancy way, perhaps using filter?
Luis
I am assuming you need the object that has key as name
You can get use of find method
let array = [
{ "key": "age", "value": 81 },
{ "key": "name", "value": "Luis" }
]
let your_obj = array.find(element=>element.key === 'name')
console.log(your_obj) // this will give you the object you need
This will give results with key name
names = [
{ "key": "age", "value": 81 },
{ "key": "name", "value": "Luis" }
]
result = names.filter(name => name.key === 'name')
I'me new to JavaScript. In the browser I receive a long dictionary like this:
{"cat": "4" , "dog": "5", "fish": "9" }
I'm wondering what is the most efficient way to convert it to a JSON object like:
[
{
"name": "cat",
"value": "4"
},
{
"name": "dog",
"value": "5"
},
{
"name": "fish",
"value": "9"
}
]
You can Loop through it and push each key-value-pair to an Array.
var tValue = {"cat": "4" , "dog": "5", "fish": "9" };
var tList = [];
for(var tKey in tValue) tList.push({name: tKey, value: tValue[tKey]});
console.log(tList);
You can just loop over the dictionary object keys using Object.keys() method, and use .map() method to transform each iterated key/value pair to the appropriate object:
var results = Object.keys(obj).map(function(k) {
return {
name: k,
value: obj[k]
};
});
Demo:
var obj = {
"cat": "4",
"dog": "5",
"fish": "9"
};
var results = Object.keys(obj).map(function(k) {
return {
name: k,
value: obj[k]
};
});
console.log(results);
You can use the function Object.entries to get every key-value pairs and with the function map build the desired output.
let obj = {"cat": "4" , "dog": "5", "fish": "9" },
result = Object.entries(obj).map(([name, value]) => ({name, value}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can do this by this way :
Call a for in loop and read your first object
Push the name and the value in your new object one by one..
Sample code :
var a = {"cat": "4" , "dog": "5", "fish": "9" };
var newJSON = [] ;
console.log(a);
for ( key in a ) {
newJSON.push({name : key, value : a[key]});
}
console.log(newJSON);
You can have this kind of formatted object
{
animals : [
{"name":"cat", "value": 4},
{"name":"dog", "value": 5},
{"name":"fish", "value": 9}
]
}
or like this
[
{"name":"cat", "value": 4},
{"name":"dog", "value": 5},
{"name":"fish", "value": 9}
]
I have an array of objects. I would like to reformat into a new array but am not sure how to begin. I have jQuery and Underscore available.
Here is my original array:
var myArray = [
{
"name": "Product",
"value": "Car"
},
{
"name": "Product",
"value": "Boat"
},
{
"name": "Product",
"value": "Truck"
},
{
"name": "Color",
"value": "Blue"
},
{
"name": "Location",
"value": "Store"
}
];
Here is what I am trying to make the new Array look like:
var newArray = [
{
"name": "Product",
"value": "Car Boat Truck"
},
{
"name": "Color",
"value": "Blue"
},
{
"name": "Location",
"value": "Store"
}
];
In the newArray the Products are all in one object.
You can use the groupBy method to get all the elements with the same name together, then map to transform them into what you want. And pluck is useful here to combine the values in the output array.
Here's quick, simple solution:
var newArray = _.chain(myArray)
.groupBy("name")
.map(function(a) {
return {
"name": a[0].name,
"value": _.pluck(a, "value").join(" ")
};
})
.value();
Demonstration
And just for completeness, here's the non-chained version:
var newArray = _.map(_.groupBy(myArray, "name"), function(a) {
return {
"name": a[0].name,
"value": _.pluck(a, "value").join(" ")
};
});
Here's a more generalized solution that's reusable and not hard-coded. This way, you can create multiple groupBy methods for different properties of different object collections, then join the properties that you require. jsFiddle
function groupBy(groupBy) {
return function(source, joinOn) {
return _.each(_.groupBy(source, groupBy), function(val, key, context){
context[key] = _.pluck(val, joinOn).join(' ');
});
};
}
var groupByNameOn = groupBy('name');
console.log(groupByNameOn(arr, 'value'));