I need to check key exist in object of object. I have array of object and in every object i have one other object. I need to check the key is existing in object of object
var myarr = [{
hello: "world",
payload: {
kekek: 'sdfsdfsdf',
baby: 'sdfsdfsdfds'
}
},
{
hello: "world",
payload: {
qwe: 'sdfsdfsdf',
baby: 'sdfsdfsdfds'
}
}, {
hello: "world",
payload: {
qwe: 'sdfsdfsdf',
baby: 'sdfsdfsdfds'
}
},
{
hello: "world",
payload: {
asdf: 'sdfsdfsdf',
baby: 'sdfsdfsdfds'
}
}
]
let pp = myarr.payload.hasOwnProperty('eekey')
console.log(pp).
I need to check kekek in payload.
If I understood correctly, you want to check if every of object of your array contains a specific key in payload property. If so, you can use in operator to check if a property is present in a object. You can improve this snippet by checking if value is defined.
let key = 'kekek';
const everyObjectHasKey = myarr.every(item => item.payload && key in item.payload);
console.log(everyObjectHasKey);
In this link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every , you can see more about every method for arrays
Related
I have a JSON object that will sometimes be an object (a single instance) and sometimes be an array (multiple instances of the object). I need to write an if statement that basically says if this section of JSON is an object, wrap it in an array containing that single object, and if it's an array containing multiple objects, return that array. In either instance I'm returning an array containing either 1 or multiple objects.
Here is what the JSON looks like when it is NOT an array.
"link": {
"values": {
"key1": "value1",
...
"key8": "value8"
},
"key9": "value9"
}
And it should look like this when it's an array:
"link": [{
"values": {
"key1": "value1",
...
"key8": "value8",
},
"key9": "value9"
}]
EDIT -----------------------------
This is what I've written so far that is producing the type error I'm experiencing.
const isLinkArray = sections.values;
isLinkArray.link = Array.isArray(isLinkArray.link) ? isLinkArray.link : [isLinkArray.link];
EDIT 2 ---------------------------
The final answer ended up being almost identical to Kinglish' answer, so I figured I would post it here. The issue I ran into was that the JSON right above 'link' was also an array and that was causing the typescript error.
const sectionsWithLinkArray = sections.map((section) => {
return {
values: {
...section.values,
link: !Array.isArray(section.values.link) ? [section.values.link] : section.values.link,
},
};
});
You can use Array.isArray to check, then convert
let data = {
"link": {
"values": {
"key1": "value1",
"key8": "value8"
},
"key9": "value9"
}
}
data.link = Array.isArray(data.link) ? data.link : [data.link];
console.log(data)
This can be done by writing a simple function that checks if it's an array.
const returnArray = (value) => {
if (Array.isArray(value) {
return value;
}
return
}
updated the answer of #Kinglish to typescript one because you cannot change types of defined value as it giving error for this either simply ignore the typescript or define types that simply accept link in object and array of object or just created new variable that expect a link in the array and wrap it inside data by simply doing this:
const data = {
link: {
values: {
key1: 'value1',
key8: 'value8',
},
key9: 'value9',
},
};
// This is the type of data you can't change it by default and it doesn't expect array of object of `link`.
// const data: {
// link: {
// values: {
// key1: string;
// key8: string;
// };
// key9: string;
// };
// };
const linkArray = { link: Array.isArray(data.link) ? data.link : [data.link] };
// Now this is the type of linkArray that expect array of object of `link`
// const linkArray: {
// link: {
// values: {
// key1: string;
// key8: string;
// };
// key9: string;
// }[];
// };
console.log('data', data);
console.log('linkArray', linkArray);
My object
object1 ={
name: xxx,
Id: 212
}
I need a output like:
{
212:xxx
}
Can anyone help me to do it?
for(var key in object1) {
if(object1.hasOwnProperty(key))
{
console.log( eachPeriod[key]);
}
}
You can set the key of the object with a variable enclosed with brackets as [Id]. The convert() function takes the object as an argument and assigns the value of name and Id to the corresponding variables by destructuring. Then, use those variables to construct the object.
const obj = {
name: 'xxx',
Id: 212
};
function convert ({ name, Id }) {
return {
[Id]: name
};
}
console.log(convert(obj));
I have the following JSON object:
{
id: "id string",
test: {
everything inside test
},
rest_id: "rest_id string"
}
I want to re-format the object a bit so it is as follows:
{
everything inside test,
id: "rest_id string" // pulled from rest_id
}
and finally need to get the rid of the original id property. What is the best way for me to re-format this JSON object?
You can create a new object with the properties you want using a destructuring assignment
const before = {
id: "id string",
test: {
foo: 'foo',
bar: 'bar',
baz: 'baz',
id: 'i will be lost'
},
rest_id: "rest_id string"
}
const after = {
...before.test,
id: before.rest_id
}
console.log(after)
Note that if there are any id properties in test, they will be lost.
Use Object.assign to promote the contents of the inner object, then the delete operator to delete the inner object and the unwanted id key.
let input = {
id: "some string",
test: {
someKey: 'someValue'
},
rest_id: "some string"
}
input = Object.assign(input, input.test)
delete input.test
delete input.id
console.log(input)
You should first verify if obj and obj.test exist, if they do iterate through all properties in obj.test and write them to obj.
Then you can replace obj.id with obj.rest_id if it exists.
The old properties can be deleted safely.
let obj = {
id: "some string",
test: {
something: "hey hey hey",
something_else: "ok",
also_this: "alright"
},
rest_id: "some other string"
}
if (obj && obj.test) {
if(Object.keys(obj.test).length) {
Object.keys(obj.test).forEach((key, value) => {
obj[key] = value
});
}
delete obj.test
}
if (obj && obj.rest_id) {
obj.id = obj.rest_id
delete obj.rest_id
}
console.log(obj)
The Problem:
I have this function. Which removes all KeyValue Pairs that have an Empty String as value from a Payload.
The problem is, that I want to apply it in an Object that is Nested. Not the whole Payload Object. Example:
configuration: {
conf1: "",
conf2: "Something",
conf3: ""
},
resourceName: "Name"
In this case I want to apply my UtilityFunction, in the configurationObject. Which would result in this:
configuration: {
conf2: "Something",
},
resourceName: "Name"
So, I used a few Methods. Object.assign, rest, in order to supply an object with all the outside parameters, but also, the output of the utility applied to just the configuration object.
I tried:
Object.assign(formValues, removeEmptyKeysUtil(formValues.configuration));
// Results in printing the values in the main object.
Also:
{ formValues, ...removeEmptyKeysUtil(formValues.configuration) };
// which does not do anything
Can you please help me, and explain what am I doing wrong?
The stripEmptyStrings function takes the original object and the target key.
this function can also handle if the target property of the object is "" and will delete that property regardless of if it is an Object or not.
const stripEmptyStrings = (object, target) => {
const _target = object[target];
if (_target === "") {
delete object[target]
return object;
}
else if (typeof _target === "object") {
Object.keys(_target).forEach((k) => {
if (_target[k] === "") delete _target[k];
})
}
return {
...object,
[target]: _target,
}
}
const obj1 = {
configuration: {
conf1: "",
conf2: "Something",
conf3: ""
},
resourceName: "Name",
}
const result1 = stripEmptyStrings(obj1, "configuration");
console.log(result1)
const obj2 = {
removeMe: "",
resourceName: "Name2",
}
const result2 = stripEmptyStrings(obj2, "removeMe");
console.log(result2)
I have a data object in vue that looks like this
rows[
0 {
title: "my title",
post: "my post text",
public: false,
info: "some info"
},
1 {
title: "my title",
post: "my post text"
public: true,
info: "some info"
},
2 {
title: "my title",
post: "my post text"
public: false,
info: "some info"
}
]
I then copy that object and remove certain properties if needed before posting the object to my backend like this:
var postData = this.rows;
postData.forEach(function(o) {
if (o.public === true) {
delete o.info;
}
});
var uploadData = {};
uploadData.blogpost = postData;
axios({
method: 'post',
url: myUrl,
responseType: 'json',
data: uploadData
})
The problem is that delete o.info; will also remove the property from my vm root data, and I dont understand why since I created a new varible/copied the root data into that one. So how can I remove certain object properties from my data before posting it without altering my root data vm in vue ?
You need to take a copy of your data by cloning it. There are various ways of cloning the data, I would recommend using lodash's function, cloneDeep
import _ from 'lodash'
...
postDataCopy = _.cloneDeep(postData)
Then you can modify postDataCopy as you like without modifying the original.
this is because in javascript objects are copied-by-reference which means though you are changing postData which actually is referencing to original address that holds the data i.e. rows. you can do this
postData = JSON.parse(JSON.stringify(rows))
You need to make a copy of your referenced variable.
// ES6
let copiedObject = Object.assign({}, originalObject)
it is because row is reference type and postData is pointing to same reference as row. To copy without reference (deep copy) you can use Object.assign if your object/array contains only value type ( like number, string , boolean etc) not reference type like Object or Array. If your Object contains reference type like object containing object then internal copied object will be reference type.
Example 1:
var user = {
name: "abc",
address: "cde"
};
var copiedUser = Object.assign({}, user);
it copies properties from user. So user and copiedUser are different object because user contains only value types
Example 2:
var user = {
name: "abc",
address: "cde",
other_info: { // reference type
country: "india"
}
};
var copiedUser = Object.assign({}, user);
Now it copies all properties from user but user contains other_info that is reference type(object). so changing copiedUser properties which are value type will not affect user but changing other_info of copiedUser or user will affect each other.
copiedUser.name ="new name"; // will not reflect in user
copiedUser .other_info.country = "new country"; // will reflect in user also
So Object.assign will copy to one level. If your object contains nested object or array you need to iterate and copy till last level.
Object.assign takes {} as well as [] also. so you can return array also.
eg:var copiedArray= Object.assign([], [1,3,4,5]);
So for your case I think you need to iterate your array till object then copy and push them in another array;
var rows = [
{
title: "my title",
post: "my post text",
public: false,
info: "some info"
},
{
title: "my title",
post: "my post text",
public: true,
info: "some info"
},
{
title: "my title",
post: "my post text",
public: false,
info: "some info"
}
];
var postData = [];
for(var i=0;i<rows.length;i++) {
postData.push(Object.assign({}, rows[i]));
}
Reactivity is caused by Observer _proto inside each object and array.
You can use the following object util as mixin if needed to remove ovservable hatch from each object.
const isEmpty = (value) => {
if (!value) return false;
if (Array.isArray(value)) return Boolean(value.length);
return value ? Boolean(Object.keys(value).length) : false;
};
const isNotEmpty = value => isEmpty(value);
const clone = (value) => {
if (!value) return value;
const isObject = (typeof value === 'object');
const isArray = Array.isArray(value);
if (!isObject && !isArray) return value;
// Removing reference of Array of values
if (isArray) return [...value.map(val => clone(val))];
if (isObject) return { ...value };
return value;
};
const merge = (parent, values) => ({ ...parent, ...values });
export {
isEmpty,
isNotEmpty,
clone,
merge
};
And in store getters .
import { clone } from '#/utils/object';
const getData = state => clone(state.data);
export default {
getData
}