Home > Mobile >  Combine object values and create array
Combine object values and create array

Time:08-11

I have an object that looks in the following format with a lot of data

const obj = {
  firstItem1: "Main",
  secondItem2: "Something",
  thirdItem3: "",
  firstItemNumber1: "test",
  secondItemNumber2: "bx",
  thirdItemNumber3: ""    
}

If the string is empty, ignore it and dont add to array I would like to return it in the following format

firstItem1 firstItemNumber1

Output should be an array of strings.

["Main test", "Something bx"]

CodePudding user response:

store the valid values in an seperate array ( here singleItem ) and then convert it to string with join method and append to the output array ( here data )

Like this, and wrap it inside a function...

const obj = {
    firstItem1: "Main",
    secondItem2: "Something",
    thirdItem3: "",
    firstItemNumber1: "test",
    secondItemNumber2: "bx",
    thirdItemNumber3: "",
};

function filterValues(obj) {
    var data = [];
    var singleItem = [];

    Object.values(obj).forEach((o) => {
        if (!o || o == "") {
            data.push(singleItem.join(" "));
            singleItem = [];
        } else singleItem.push(o);
    });

    return data;
}

console.log(filterValues(obj));

CodePudding user response:

If you want to receive the array of object fields, use:

Object.keys(obj)

If you want to receive the array of object values, use:

Object.values(obj)

In your case, you can use Object.entries(obj), it returns you array of array with key and value. Logic of iteration you can find below.

You need to specify/give us the rule/logic how to map field to field - by name, etc..

const obj = {
  firstItem1: "Main",
  secondItem2: "Something",
  thirdItem3: "",
  firstItemNumber1: "test",
  secondItemNumber2: "bx",
  thirdItemNumber3: ""    
};
Object.entries(obj).filter(arr => {
    const [field, value] = arr
    return value?.length; // remove empty strings
}).map((arr, index, originalArray) => {
    const [field, value] = arr
    //return your string here by your specific rule/logic
    
})

CodePudding user response:

First, you need to get keys and values of the obj, then group it by the number first, second, third, ..., with reduce method, To be in this format.

{
   first: ['Main', 'test'],
   second: ['Something', 'bx']
}

Then get values from this Object, and join it with a space.

let numbers = ["first", "second", "third"];



const obj = {
  firstItem1: "Main",
  secondItem2: "Something",
  thirdItem3: "",
  firstItemNumber1: "test",
  secondItemNumber2: "bx",
  thirdItemNumber3: ""    
}

const result = Object.values(Object.entries(obj).reduce((acc, [key, value]) => {
    let number = numbers.find(n => key.startsWith(n))
    if (value !== '') {
      acc[number] ? acc[number].push(value) : (acc[number] = [value])
    }
    return acc;
}, {})).map(i => i.join(' '))

console.log(result)

CodePudding user response:

You can get the keys from object by using Object.Keys() and then store the strings with similar names and using array map and filter you can return the desired result.

const obj = {
  firstItem1: "Main",
  secondItem2: "Something",
  thirdItem3: "",
  firstItemNumber1: "test",
  secondItemNumber2: "bx",
  thirdItemNumber3: ""    
};

const strArray = Object.keys(obj);

const tempArray = [];

const getSimilarKeys = arr => arr.forEach((item, index) => {
  if(!item.includes('Number')){
    tempArray.push(item);
  }
});

getSimilarKeys(strArray);

const result = tempArray.map((item, index) => obj[item]   ' '    obj[`${item.substring(0, item.length - 1)}Number${index 1}`]).filter(item => item !== ' ');


console.log('result ', result)

CodePudding user response:

Another possible solution.

const obj = {
    firstItem1: "Main",
    secondItem2: "Something",
    thirdItem3: "",
    firstItemNumber1: "test",
    secondItemNumber2: "bx",
    thirdItemNumber3: ""
}

    const someArr = Object.keys(obj).reduce((arr, next) => 
    !next.includes('Number') && obj[next] 
      ? (arr.push(`${obj[next]}, ${obj[next.toString().replace('Item', 'ItemNumber')]}`), arr) 
      : arr, []);

console.log(someArr);

  • Related