0
myArray   = ['1', '2', '3'];

myObj     = { 1-vehicle : 'car', 2-vehicle : 'bike', 3-vehicle : 'train' };

resultObj = {
    '1': { '1-vehicle': 'car' }, 
    '2': { '2-vehicle': 'bike' },
    '3': { '3-vehicle': 'train' }
};

I am having an object where each key is starting with a number and also I have and array with some values. I am trying to match those key and values and split up the object. Please help me. Thanks in advance.

I have tried it and i am posting my code below but I am not successful

{
    Object.keys(myObj).filter((key: any) => {
        for (const i in myArray) {
            if (myArray[i] === key.charAt(0)) {
                newObj[key] = myObj[key]
                resultObj[myArray[i]] = newObj
            }
        }
    })
}
7
  • 2
    Your final result has not correct format. Commented Jan 17, 2019 at 9:03
  • Thanks! I have edited the question Commented Jan 17, 2019 at 9:07
  • 2
    it is neither an array nor an object. Commented Jan 17, 2019 at 9:07
  • sorry my bad. changed to object Commented Jan 17, 2019 at 9:12
  • 2
    maybe a word is necessary. by taking changing keys, which requires more information like a given array or if you need to split the keys for getting adddtional information, you may better use an array with objects who have same key names and all other information is stored inside of the object with the same key, like an id. Commented Jan 17, 2019 at 9:12

2 Answers 2

3

You could map the wanted parts and assign objects to a single object.

This solution feature a closure over the combined key of the object.

var array = ['1' , '2' , '3'],
    object = { '1-vehicle': 'car', '2-vehicle': 'bike', '3-vehicle': 'train' },
    result = Object.assign(
        ...array.map(v => (k => ({ [v]: { [k]: object[k] } }))(v + '-vehicle'))
    );

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

2
var res = {};
for(let k in myObj){
  if(k[0])res[k[0]]= {[k]:myObj[k]};
}

the simplest and shortest solution is

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.