I have an Object
let data = {
a: 1,
b: 2,
c: {
abc: "ak",
bcd: "gh",
cfv: "ht"
}
}
then I have variables which I need to show with these object value
let abc = "first 1", bcd="sec2", cfv="third3" , def="fourth 4", tdf = "fifth 5";
Now the Object will come in API call it can be any of these variable.
How can I match the variable name with the object data.c.(object key) and concatinate their value.
for example the output should be
As we have (abc, bcd, cfv) as our object key then the output would be
first 1ak ==> that is the value of (abc + data.c["abc"])
sec2gh ==> that is the value of (bcd + data.c["bcd"])
third3ht ==> that is the value of (cfv + data.c["cfv"])
I tried using Object.keys() method so from this method we will get the object keys in array then how can I match with the variable name -
Object.keys(data.c);
==> ["abc", "bcd", "cfv"] (After this how can I proceed to match the variable and show their values?)
Shall I loop throught the object that (data.c)?
Please help me giving some ideas to achieve this implementation.
thank you
If it's possible for you to amend the format of your abc, bcd etc. variables to be the properties in an object, then this problem becomes trivial. You can use flatMap() to create a new array of the output values by linking the properties of the two target objects, like this:
let values = {
abc: "first 1",
bcd: "sec2",
cfv: "third3",
def: "fourth 4",
tdf: "fifth 5"
}
let data = {
a: 1,
b: 2,
c: {
abc: "ak",
bcd: "gh",
cfv: "ht"
}
}
let output = Object.keys(values).flatMap(k => data.c.hasOwnProperty(k) ? values[k] + data.c[k] : []);
console.log(output);
Related
I am trying to access an object within an object using the key from another object.
I have two objects:
const OutputReference = {Key1: "Some Random String",Key2: "Some Random String"}
const masterKey = {
...
'Key1':{
Label: "Key 1",
view: [1,2,3],
},
'Key2':{
Label: "Key 2",
view: [4,5,6],
},
...
}
OutputReference contains multiple keys and values, and I want match these keys to the keys in masterKey to grab each corresponding 'view'. So far, I use this function to break out OutputReference into a key (k) and value (v):
Object.keys(OutpufReference).filter(([k,v])=>{
...
//code here
...
});
I then want to grab "view" for the corresponding key and store it in an array. I used:
var tempArr = []
tempArr.push(masterKey.k.view)
Making the entire function:
Object.keys(OutpufReference).filter(([k,v])=>{
...
var tempArr = []
tempArr.push(masterKey.k.view)
...
});
The issue is masterKey.k is coming back undefined. Note console.log(k) in this case outputs exactly this: Key1
What I have tried (just to access k):
tempArr.push(masterKey.k)
tempArr.push(masterKey[k])
var temp = JSON.stringify(k)
tempArr.push(masterKey[temp])
Object.keys(masterKey).forEach((v,i)=>{
if(v === k) //k is the index from mapping OutputReference
tempArr.push(masterKey.v)
})
None of these work; all return an undefined object (masterKey.v, masterKey[temp], etc.). Note, when doing console.log() on each of these keys (temp, v, k), it outputs the string Key1. However, using
tempArr.push(masterKey.Key1)
Places the correct value in tempArr (Being the object Key1). This is not ideal however, as there are many keys and values in masterKey and OutputReference only contains a few of them.
Where I looked
I researched mozilla's guide on objects, which led me to my previous attempts Mozilla. I also researched this thread Deleting a property from a javascript object.
However it recommends what I have already tried.
I see from this thread that JavaScript objects can only use strings as keys, so why doesn't stringifying my key in
var temp = JSON.stringify(k)
tempArr.push(masterKey[temp])
work?
The final output desired: The array tempArr containing every view that outputReference matched with masterKey (In this case: tempArr = [[1,2,3],[4,5,6])
If I understood correctly, your end goal is to insert in each position of the array tempArr the value of the property "view" nested inside of the first level properties of the masterKey object. But you only want to push to the tempArr keys that are contained inside of the OutputReference object.
The code below will push the arrays inside of each view property nested in the properties Key1 and Key2 into tempArray.
const OutputReference = {
Key1: "Some Random String",
Key2: "Some Random String"
}
const masterKey = {
'Key1': {
Label: "Key 1",
view: [1, 2, 3],
},
'Key2': {
Label: "Key 2",
view: [4, 5, 6],
}
}
const tempArr = []
for (keys in OutputReference) {
if (Object.hasOwn(masterKey, keys)) {
tempArr.push(masterKey[keys]["view"])
console.log('The following content is being pushed to the array: ', masterKey[keys]["view"])
}
}
console.log('This is the content of tempArray:', tempArr)
Alternatively you can use
const OutputReference = {
Key1: "Some Random String",
Key2: "Some Random String"
}
const masterKey = {
'Key1': {
Label: "Key 1",
view: [1, 2, 3],
},
'Key2': {
Label: "Key 2",
view: [4, 5, 6],
}
}
const tempArr = []
Object.keys(OutputReference).forEach((key, value) => {
if (Object.hasOwn(masterKey, key)) {
tempArr.push(masterKey[key]["view"])
}
console.log('The following content is being pushed to the array: ', masterKey[key]["view"])
})
console.log('This is the content of tempArray:', tempArr)
I hope this works for you
You were close, but instead of filter, use map on the object keys to create the array
tempArr = Object.keys(OutputReference).map(m => masterKey[m].view)
const OutputReference = {
Key1: "Some Random String",
Key2: "Some Random String"
}
const masterKey = {
'Key1': {
Label: "Key 1",
view: [1, 2, 3],
},
'Key2': {
Label: "Key 2",
view: [4, 5, 6],
},
'Key3': {
Label: "Key 3",
view: [4, 5, 6],
},
}
const tempArr = Object.keys(OutputReference).map(m => masterKey[m].view)
console.log(tempArr)
My usage will contain 6 different object types (some which contain double nested arrays), and any possibility of number of entries, on the condition that an given entry is unique.
These objects do not have a consistent unique identifier (a unique identifier is applied in backend on submission).
here is an example of what the array may look like (only 2 object types):
arr = [
{name:"aaa",time:15},
{name:"aaa",time:22},
{timeline: "250", chars[{a},{b},{c}]},
{timeline: "220", chars[{d},{e},{f}]},
]
obj = {name:"aaa",time:22}
My intention is to gain a true or false based on if obj is inside arr
I have tried methods:
I was suggested this method & it errors: #<Object> is not a function
console.log(arr.find(obj))
I also found this suggestion but it will always return false even with the element present
console.log(arr.includes(object))
I tried this method myself, though it will always fail.
console.log(arr.filter((element, index) => element === obj)
With attempt 4, If I was to compare name, this would be insufficient as unique time would be ignored missing valid entries.
If I was to pass every field, this would also not work as each object may or may not have the field and cause error.
Its not really possible to manually pre-filter filter into distinct categories, as every time a new type is added it will need manually adding to the filter.
If there is a library which could do this that you know of, please let me know as that would be perfect. Otherwise any other suggestions (excluding separating arrays) Would be greatly appreciated.
Use arr.some() to check if the required object is present in the array.
To compare the objects, a simpler way is to Stringify both the Objects and compare them.
const arr = [
{name:"aaa",time:15},
{name:"aaa",time:22},
{name: "aaa", chars: ["a", "b", "c"]},
{name: "bbb", chars: ["d", "e", "f"]},
]
const obj1 = {name:"aaa", time: 15}
const obj2 = {name:"aaa",chars: ["a", "b", "c"]}
console.log(arr.some((element) => JSON.stringify(element) === JSON.stringify(obj1))) // true
console.log(arr.some((element) => JSON.stringify(element) === JSON.stringify(obj2))) // true
Didn't give much thought on performance.
I didn't put much thought on performace here but this might help:
function checkObjectInArray(arr, obj) {
const res = arr.some((el) => deepEqual(el, obj));
console.log(res);
}
function deepEqual(obj1, obj2) {
if (Object.keys(obj1).length !== Object.keys(obj2).length) return false;
for (let prop in obj1) {
if (!obj2.hasOwnProperty(prop) || obj2[prop] !== obj1[prop]) {
return false;
}
}
return true;
}
in your case you can use it like:
arr = [
{ name: "aaa", time: 15 },
{ name: "aaa", time: 22 },
{ timeline: "250", data: ["2", "3", "4"] },
{ timeline: "251", data: ["2", "3", "4"] }, // what is chars[{d},{e},{f}] ?!
];
obj = { name: "aaa", time: 22 };
checkObjectInArray(arr, obj);
Observation : arr is not a valid array. Nested chars is not containing a valid value.
Solution : You can simply achieve the requirement by Just converting the JSON object into a JSON string and by comparing.
This solution works fine as you are just trying to find a single object in the passed arr.
Live Demo :
const arr = [
{name:"aaa",time:15},
{name:"aaa",time:22},
{timeline: "250", chars: [{a: 1},{b: 2},{c: 3}]},
{timeline: "220", chars: [{d: 4},{e: 5},{f: 6}]},
];
const obj = {name:"aaa",time:22};
const res = JSON.stringify(arr).indexOf(JSON.stringify(obj)) !== -1 ? true : false;
console.log(res);
I'm building a logger service. First argument is "msg" string and the second one in array of parameters (can be array or objects)
How can i iterate this parameters array and print in the console so the object/array can be seen\expand\collapse in the console?
For example if it's not dynamic i would do something like this:
console.log('str', obj1, obj2, obj3)
You mean something like this?
let arrayOfObjects = [
{ a: 1, b: 2 },
{ a: 3, b: 4, c: 5 }
];
let testMessage = "This is just a message";
console.log(testMessage, Object.values(arrayOfObjects));
I was just wondering if there are any differences between these ways of JSON object declaration or they do the same thing? What is the standard (recommended) way to declare an object?
According to my test, they both give the same result.
let data1 = {
"record_1": [1,2,3],
"record_2": [4,5,6]
}
let data2 = {
record_1: [1,2,3],
record_2: [4,5,6]
}
console.log(data1);
console.log(data2);
console.log(data1.record_1);
console.log(data2.record_1);
console.log(data1.record_2);
console.log(data2.record_2);
console.log(JSON.stringify(data1));
console.log(JSON.stringify(data2));
Output:
{
record_1:(3) [...],
record_2:(3) [...]
}
{
record_1:(3) [...],
record_2:(3) [...]
}
(3) [
1,
2,
3
]
(3) [
1,
2,
3
]
(3) [
4,
5,
6
]
(3) [
4,
5,
6
]
{"record_1":[1,2,3],"record_2":[4,5,6]}
{"record_1":[1,2,3],"record_2":[4,5,6]}
Both of the declarations are valid in Javascript
let data1 = {
"record_1": [1,2,3],
"record_2": [4,5,6]
}
let data2 = {
record_1: [1,2,3],
record_2: [4,5,6]
}
but when it comes to JSON , data2 is invalid JSON syntax. You can verify at https://jsonlint.com/
One more diff is as below:
var obj = { "some key" : "Val" }; // Valid in JS
var obj = { some key : "Val" }; // invalid in JS
So for JS , both of these deceleration plays different role depending on the situation. Normally, data2 type declaration is widely used.
Object's property name are of type string, if you provide any other type then that is automatically converted to string.
var obj = {1: "one"}
var keyName = Object.keys(obj)[0];
console.log(`key Name ${keyName} and type is ${typeof keyName}`);
I will prefer the explicit way (using the quotes) of declaration as this will reduced the confusion (from the reader of the code).
They're essentially the same. One difference is that when you use quotes, you can use special characters as key.
// invalid
const noQuotes = {
key with spaces: 123
}
// valid
const withQuotes = {
"key with spaces": 123
}
I have some issues to organize my code.
Here is an example of what i would like to do:
var Test = {
old: [
get: function(who, when){
returrn({ subject: "Old test 001", text: "The test 001 was perform by "+who });
},
get: function(who, when){
returrn({ subject: "Old test 002", text: "The "+when+" the test 002 was performed"});
}
],
new: [
//Same thing
]
};
The thing is, we apparently can't do that, so i am wondering which is the way to declare functions in an Array ?
I need to do that because each method get() of the array can return a different message and the message can include the variables passed in parameters at different positions in the text, so i have to declare it explicitly.
I don't do like this:
var Test = {
old: [
one: {
get: function(who, when){
returrn({ subject: "Old test 001", text: "The test 001 was perform by "+who });
},
},
two: {
get: function(who, when){
returrn({ subject: "Old test 002", text: "The "+when+" the test 002 was performed"});
}
}
],
new: [
//Same thing
]
};
Because i need to access the content dynamically, like Test.old[test_id].get("toto", "02/04/2013"). and we unfortunatelly can't index things by numerical values in JSON.
However i'll do it like this is there is nothing better.
So what is the best thing to do in this context ?
Thanks !
The question is vague and confusing, but I can see why your code doesn't work. You're conflating arrays and objects. Array literals look like this:
var myArray = [
"first item",
"second item",
{value: "third item"},
["first/only item in fourth item"],
1,
2,
3.14159,
function(a,b) { return a + b; },
"etc."
];
Items in an array are accessed using push, pop, shift, unshift, and numerical indexes.
Object literal look like this:
var myObject = {
one: "some value",
two: {
value: "object values can be anything"
},
123: 456,
"a million": function (a, b) { return a - b; }
};
Items in an object are access using string indexes.
And finally, do you have a returrn() function declared somewhere? In either case, why not just return your return values?